zoukankan      html  css  js  c++  java
  • 2.4.5 Fractions to Decimals

    Fractions to Decimals

    Write a program that will accept a fraction of the form N/D, where N is the numerator and D is the denominator and print the decimal representation. If the decimal representation has a repeating sequence of digits, indicate the sequence by enclosing it in brackets. For example, 1/3 = .33333333...is denoted as 0.(3), and 41/333 = 0.123123123...is denoted as 0.(123). Use xxx.0 to denote an integer. Typical conversions are:

    1/3     =  0.(3)
    22/5    =  4.4
    1/7     =  0.(142857)
    2/2     =  1.0
    3/8     =  0.375
    45/56   =  0.803(571428)
    

    PROGRAM NAME: fracdec

    INPUT FORMAT

    A single line with two space separated integers, N and D, 1 <= N,D <= 100000.

    SAMPLE INPUT (file fracdec.in)

    45 56
    

    OUTPUT FORMAT

    The decimal expansion, as detailed above. If the expansion exceeds 76 characters in length, print it on multiple lines with 76 characters per line.

    SAMPLE OUTPUT (file fracdec.out)

    0.803(571428)
    
    /*
    ID: makeeca1
    PROG: fracdec
    LANG: C++
    */
    #include <iostream>
    #include <cstdio>
    #include <string>
    #include <cstring>
    #include <sstream>
    #define MAX 1000000
    using namespace std;
    int n,m,pos[MAX];
    string s;
    string getstring(const int n){
        std::stringstream newstr;
        newstr<<n;
        return newstr.str();
    }
    int main(){
        freopen("fracdec.in","r",stdin);
        freopen("fracdec.out","w",stdout);
        scanf("%d%d",&n,&m);s="";
        if (n%m==0){printf("%d.0
    ",n/m);return 0;}
        s=getstring(n/m)+".";
        n=n%m*10;
        for (;;){
            pos[n]=s.size();
            s=s+getstring(n/m);
            n=n%m*10;
            if (pos[n]!=0) s=s.substr(0,pos[n])+"("+s.substr(pos[n],s.size()-pos[n])+")";
            if (n==0 || pos[n]!=0)break;
        }
        for (int i=1;i<=s.size();i++){
            printf("%c",s[i-1]);
            if (i%76==0)printf("
    ");
        }
        printf("
    ");
        return 0;
    }
  • 相关阅读:
    单元测试利器 JUnit 4 Mr
    firefox插件介绍 Mr
    js函数使用技巧集合 Mr
    单点登录
    2.SilverLight动态加载控件
    3.如何获取动态生成的SL控件的NAME值(一)
    ASP.Net中控件的EnableViewState属性 【转】
    三种在ASP.NET中重写URL的方法
    SQLHelper.cs
    c# IS与AS的使用方法
  • 原文地址:https://www.cnblogs.com/makeecat/p/3274642.html
Copyright © 2011-2022 走看看