Decimal

Description

任意一个分数都是有理数,对于任意一个有限小数,我们都可以表示成一个无限循环小数的形式(在其末尾添加0),对于任意一个无限循环小数都可以转化成一个分数。现在你的任务就是将任意一个无限循环小数转化成既约分数形式。所谓既约分数表示,分子和分母的最大公约数是1。

Input

有多组数据。

每组数据一行。输入为0.a1a2a3...ak(b1b2...bm)的形式,其中a1a2a3...ak为非循环部分,(b1b2b3..bm)为循环部分。数据保证非循环部分的长度k和循环部分的长度m不会超过8. 

Output

对于每组测试数据输出A/B,其中A是分子,B是分母,A,B均为整数。

Sample Input

0.0(714285)
0.0(5)
0.9(671)

Sample Output

1/14
1/18
4831/4995
#include <stdio.h>
#include <string>
#include <string.h>
#define LL long long
#include <iostream>
using namespace std;

LL a[10],b[10];
LL pow(LL n)
{
    LL s=1;
    for(LL i=1; i<=n; i++) s*=10;
    return s;
}
LL gcd(LL a,LL b)
{
    if(b==0) return a;
    else return gcd(b,a%b);
}

int main()
{
    //freopen("a.txt","r",stdin);
    char s[50];
    while(scanf("%s",s)!=EOF)
    {
        LL i,j,m=0,k=0;
        for(i=2; i<strlen(s); i++)
        {
            if(s[i]=='(') break;
            else a[k++]=s[i]-'0';
        }
        for(j=i+1; j<strlen(s); j++)
        {
            if(s[j]==')') break;
            b[m++]=s[j]-'0';
        }
        LL t1=0,t2=0;
        for(i=0; i<k; i++) t1 += a[i]*pow(k-i-1);
        for(i=0; i<m; i++) t2 += b[i]*pow(m-i-1);

        if(m==0)
        {
            printf("%lld/",t1/gcd(t1,pow(k)));
            printf("%lld\n",pow(k)/gcd(t1,pow(k)));
            continue;
        }
        LL c=t1*(pow(m)-1) +t2;
        LL d=pow(k)*(pow(m)-1);
        //printf("%lld %lld\n",c,d);
        printf("%lld/",c/gcd(d,c));
        printf("%lld\n",d/gcd(d,c));
        getchar();
    }

    return 0;
}
View Code

 

 
posted @ 2013-09-05 09:42  1002liu  阅读(202)  评论(0编辑  收藏  举报