题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1717
小数化分数2
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2921 Accepted Submission(s): 1187
Problem Description
Ray 在数学课上听老师说,任何小数都能表示成分数的形式,他开始了化了起来,很快他就完成了,但他又想到一个问题,如何把一个循环小数化成分数呢?
请你写一个程序不但可以将普通小数化成最简分数,也可以把循环小数化成最简分数。
请你写一个程序不但可以将普通小数化成最简分数,也可以把循环小数化成最简分数。
Input
第一行是一个整数N,表示有多少组数据。
每组数据只有一个纯小数,也就是整数部分为0。小数的位数不超过9位,循环部分用()括起来。
每组数据只有一个纯小数,也就是整数部分为0。小数的位数不超过9位,循环部分用()括起来。
Output
对每一个对应的小数化成最简分数后输出,占一行。
Sample Input
3 0.(4) 0.5 0.32(692307)
Sample Output
4/9 1/2 17/52
Source
Recommend
这个题目参见百度
代码为:
#include<cstdio>
#include<cstring>
const int maxn=10+10;
char str[maxn];
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
int cal1(int x)
{
int ans=1;
for(int i=1;i<=x;i++)
ans=ans*10;
return ans;
}
int cal2(int x)
{
int ans=0;
for(int i=1;i<=x;i++)
ans=ans*10+9;
return ans;
}
int main()
{
int t,ok,len,start,end,num;
int son,mother,extra;
int ans;
scanf("%d",&t);
while(t--)
{
ok=1;
scanf("%s",str);
len=strlen(str);
for(int i=0;i<len;i++)
{
if(str[i]=='(')
{
start=i;
ok=0;
}
if(str[i]==')')
{
end=i;
ok=0;
}
}
if(ok==1)
{
son=0;
mother=cal1((len-2));
for(int i=2;i<len;i++)
son=son*10+(str[i]-'0');
// printf("mother:%lld son:%lld\n",mother,son);
ans=gcd(son,mother);
printf("%d/%d\n",son/ans,mother/ans);
}
else if(!ok&&start==2)
{
son=0;
int circle=end-1-start;
for(int i=3;i<end;i++)
son=son*10+(str[i]-'0');
mother=cal2(circle);
ans=gcd(son,mother);
printf("%d/%d\n",son/ans,mother/ans);
}
else
{
son=0;
extra=0;
int circle=end-1-start;
for(int i=2;i<start;i++)
extra=extra*10+str[i]-'0';
for(int i=start+1;i<end;i++)
son=son*10+(str[i]-'0');
mother=cal2(circle);
int copymother=cal1(start-2);
//printf("copymother%I64d\n",copymother);
// printf("extra:%lld son:%lld mother:%lld\n",extra,son,mother);
son=mother*extra+son;
ans=gcd(son,mother);
son=son/ans;
mother=mother/ans;
// printf("%lld/%lld\n",son/ans,mother/ans);
mother=mother*copymother;
ans=gcd(son,mother);
printf("%d/%d\n",son/ans,mother/ans);
}
}
return 0;
}