USACO Section 2.4 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)

题意:给你一个分式转换成小数。
分析:直接模拟除法,如果余数出现过者以后循环小数。(小技巧)
注意:每行只有76个字符
View Code
/*
  ID: dizzy_l1
  LANG: C++
  TASK: fracdec
*/
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<cstdlib>
#define MAXN 100000

using namespace std;

bool visited[MAXN];
int mod[MAXN];

string itoa(int n)
{
    if(n==0) return "0";
    string ans="";
    while(n)
    {
        ans+=(n%10+'0');
        n=n/10;
    }
    reverse(ans.begin(),ans.end());;//字符串反转函数
    return ans;
}

int main()
{
    freopen("fracdec.in","r",stdin);
    freopen("fracdec.out","w",stdout);
    string ans,t;
    int n,m,cnt,p,i;
    while(cin>>n>>m)
    {
        memset(visited,false,sizeof(visited));
        ans=itoa(n/m);
        ans+='.';
        p=ans.length();
        n=n%m;
        cnt=1;
        if(n==0)
        {
            ans+='0';
            cout<<ans<<endl;
            continue;
        }
        while(n)
        {
            if(!visited[n])
            {
                mod[cnt++]=n;
                visited[n]=true;
                ans+=itoa(n*10/m);
                n=n*10%m;
            }
            else
            {
                ans+=')';
                for(i=cnt-1;i>=1;i--)
                    if(mod[i]==n) break;
                ans.insert(i+p-1,"(");
                break;
            }
        }
        for(i=0;i<ans.length();i++)
        {
            cout<<ans[i];
            if((i+1)%76==0)cout<<endl;
        }
        if((i+1)%76!=0) cout<<endl;
    }
    return 0;
}
posted @ 2012-09-10 21:55  mtry  阅读(332)  评论(0编辑  收藏  举报