UVA 202 Repeating Decimals

这个题是很久以前的WF上的一道题,题目本身的难度不大,就是一个模拟题,自己用手模拟除法就行了,但是这题有个坑,整数部分是不会算在循环节里的,比如给个数据10/7,循环节是(428571)。我的实现思路就是判断模拟过程中余数出现重复,那么就是出现了循环节,不过模拟过程中我不断发生了错误。

具体错误就不多说了,debug过程是上UVA上找了一组别人出的数据,对拍数据,然后不断改正,加特判,还有数据边界的问题,emmmm,感觉这么写还不如看一下别人代码,可能是我这个模拟思路有点乱,但是大方向应该是一致的。下面贴代码,有时间补一下别人代码,感觉自己写的真的是惨不忍睹。

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

typedef long long ll;
int flag[3001];
int a[3001];
int b[3001];

int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    ll x,y;
    ll p,q;
    ll num;
    ll pos;
    ll ok;
    while(cin>>x>>y)
    {
        memset(flag,0,sizeof(flag));
        p=x/y;
        q=x-p*y;
        num=0;
        ok=0;
        while(1)
        {
            if(flag[q*10-q*10/y*y])
            {
                a[num]=q*10/y;
                b[num]=q*10-q*10/y*y;
                break;
            }
            a[num]=q*10/y;
            b[num]=q*10-q*10/y*y;
            flag[q*10-q*10/y*y]=1;
            num++;
            if(q*10-q*10/y*y==0)
            {
                ok=1;
                break;
            }
            q=q*10-q*10/y*y;
        }
        //cout<<num<<endl;
        if(ok==0)
        {
            for(int i=0; i<num; i++)
            {
                if(b[i]==b[num])
                {
                    pos=i;
                    break;
                }
            }
            cout<<x<<"/"<<y<<" = ";
            cout<<p<<".";
            if(a[num]==a[pos])
                num--;
            else pos++;
            for(int i=0; i<pos; i++)
            {
                cout<<a[i];
            }
            cout<<"(";
            if(num<50)
            {
                for(int i=pos; i<=num; i++)
                {
                    cout<<a[i];
                }
                cout<<")"<<endl;
            }
            else
            {
                for(int i=pos; i<50; i++)
                {
                    cout<<a[i];
                }
                cout<<"...)"<<endl;
            }
            cout<<"   "<<num-pos+1<<" = "<<"number of digits in repeating cycle"<<endl;
        }
        else
        {
            cout<<x<<"/"<<y<<" = ";
            cout<<p<<".";
            if(num==1&&a[0]==0)
            {
                cout<<"(0)"<<endl;

            }
            else
            {
                for(int i=0; i<num; i++)
                    cout<<a[i];
                cout<<"("<<0<<")"<<endl;
            }
            cout<<"   "<<1<<" = "<<"number of digits in repeating cycle"<<endl;
        }
        cout<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/zero___zero/article/details/80878359