UVa 202 - Repeating Decimals

是道算循环节的题,一开始完全没有思路,看c++的书写到大整数类模拟手算进行,再加上看了 @xuziye0327 的一篇关于数据处理的博客,有的思路。从昨天上上机课开始写,到现在,总算过了,错了好多次,细节处理总是不到位。PS:总是不长记性,上机课忘换行WA一次,最早做完的成第二了;接着做这道题,又少换行错好几次。。

#include<iostream>
#include<cstring>
#define maxn 10000
using namespace std;
int main()
{
    int a,b,i,j,k,l,t,z,y;
    int n[maxn],m[maxn];
    while(cin>>a>>b)
    {
        t=0,z=0;
        if(!a)
            goto END;
        m[0]=a%b;
        n[0]=a/b;
        if(!m[0])
        {
            cout<<a<<"/"<<b<<" = "<<n[0]<<".(0)"<<endl;
            cout<<"   1 = number of digits in repeating cycle"<<endl;
            cout<<endl;
            continue;
        }
        for(i=1;i<maxn;i++)
        {
            n[i]=m[i-1]*10/b;
            m[i]=m[i-1]*10%b;
            if(m[i]==0)
            {
                z=1;
                goto END;
            }
            for(j=i-1;j>0;j--)
            {
                if(m[i]==m[j]&&n[i]==n[j])
                {
                    for(k=j;k<=i;k++)
                        if(n[k])
                            break;
                    if(k!=i)
                        goto END;
                }
            }
        }
        END:
        if(a==0)
        {
            cout<<a<<"/"<<b<<" = "<<"0.(0)"<<endl;
            cout<<"   1 = number of digits in repeating cycle"<<endl;
        }
        else
        {
            if(z)
            {
                cout<<a<<"/"<<b<<" = "<<n[0]<<".";
                for(k=1;k<i+1;k++)
                    cout<<n[k];
                cout<<"(0)"<<endl;
                cout<<"   1 = number of digits in repeating cycle"<<endl;
            }
            else
            {
                cout<<a<<"/"<<b<<" = "<<n[0]<<".";
                for(k=1;k<j;k++)
                    cout<<n[k];
                y=k-1;
                cout<<"(";
                if(i-j<=50-y)
                    for(k=j;k<=i-1;k++)
                        cout<<n[k];
                else
                {
                    for(k=j;k<j+50-y;k++)
                        cout<<n[k];
                    cout<<"...";
                }
                cout<<")"<<endl;
                cout<<"   "<<i-j<<" = number of digits in repeating cycle"<<endl;
            }
        }
        cout<<endl;
    }
    return 0;
}


你可能感兴趣的:(uva)