题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1717
分析:
我们将这个循环小数分成三部分0.a1a2a3a4....an(b1b2bb3...bm) 分成0,不循环的部分a1a2...an,和循环节b1b2b3...bm
设这个小数为X,a1a2a3....an=s1, b1b2b3...bm=s2,y=0.(b1b2b3b4..bm)
X * 10^n = s1 + y; ---------1)
y * 10^m = s2 + y; ----------2)
由2)得 y = s2 / ( 10^m - 1 ); ------------3)
1) ,3)联立
x=( s2 + s1 *( 10^m - 1) ) / ( 10^n * ( 10^m -1 ) );
在处理的时候要注意m=0,或者n=0,的情况
代码如下:
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
LL gcd(LL a,LL b)
{
if(b) return gcd(b,a%b);
return a;
}
char a[10000];
int main()
{
int n;
scanf("%d",&n);
while(n--){
scanf("%s",a);
LL z1 = 0,cnt=0,m=0,cnt2=0,ff=100000,z2=0;
for(int i=1;i<strlen(a);i++){
if(a[i]!='.'&&a[i]!='('&&i<ff){
z1=z1*10+a[i]-'0';
if(i<ff)
cnt++;
}
if(a[i]=='(') ff=i;
if(i>ff&&a[i]!=')') z2=z2*10+a[i]-'0',cnt2++;
}
LL tmp1=1,tmp2=1,tmp,z;
for(int i=0;i<cnt;i++)
tmp1*=10;
for(int i=0;i<cnt2;i++)
tmp2*=10;
if(tmp1==1){
z=z2;
m=tmp2-1;
tmp=gcd(z,m);
printf("%I64d/%I64d\n",z/tmp,m/tmp);
continue;
}
if(tmp2==1){
z=z1,m=tmp1;
tmp=gcd(z,m);
printf("%I64d/%I64d\n",z/tmp,m/tmp);
continue;
}
z=z2+(tmp2-1)*z1;
m=tmp1*(tmp2-1);
tmp=gcd(z,m);
printf("%I64d/%I64d\n",z/tmp,m/tmp);
}
return 0;
}