uva 202 Repeating Decimals

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char change(int k)
{
    return k+'0';
}
int main()
{
    int a,b;
    int m,n;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
        m=a,n=b;
        int y[10000];
        int x=0;
        int cnt=0;
        string s;
        if(a>b) {y[x++]=a%b;a=a%b;}
        else{
            while(1)
            {
                if(cnt)
                {
                    s=s+change(a/b);
                    y[x++]=a%b;
                }
                if(a>b) break;
                a=a*10;
                cnt++;
            }
            a=a%b;
        }
        int count=0;
        int flag=0;
        while(1)
        {
            s=s+change((a*10)/b);
            y[x]=(a*10)%b;
            a=(a*10)%b;
            for(int i=0;i<x-1;i++)
            {
                if(y[i]==y[x-1]&&x>1&&s[i]==s[x-2]&&m>n) {flag=i;count++;break;}
                if(y[i]==y[x-1]&&s[i]==s[x-1]) {flag=i;count++;break;}
            }
            if(count) break;
            x++;
        }
        cout<<m<<"/"<<n<<" "<<"="<<" ";
        cout<<m/n<<".";
        for(int i=0;i<x-1;i++)
        {
            if(i==50) break;
            if(i==flag&&flag==x-2&&(s[i]>='0'&&s[i]<='9')) cout<<"("<<s[i]<<")";
            else if(i==flag&&(s[i]>='0'&&s[i]<='9')) cout<<"("<<s[i];
            else if(i==x-2&&(s[i]>='0'&&s[i]<='9'))  cout<<s[i]<<")";
            else if((s[i]>='0'&&s[i]<='9')) cout<<s[i];
        }
        if(x>50) cout<<"...)";
        cout<<endl;
        cout<<"   ";
        cout<<x-1-flag;
        cout<<" "<<"="<<" number of digits in repeating cycle"<<endl<<endl;;
    }
    return 0;
}

你可能感兴趣的:(uva 202 Repeating Decimals)