分类: C/C++
2008-04-29 22:01:42
Write a program that will accept a fraction of the form N/D, where N is the numerator and D is the denominator and print the decimal representation. If the decimal representation has a repeating sequence of digits, indicate the sequence by enclosing it in brackets. For example, 1/3 = .33333333...is denoted as 0.(3), and 41/333 = 0.123123123...is denoted as 0.(123). Use xxx.0 to denote an integer. Typical conversions are:
1/3 = 0.(3)
22/5 = 4.4
1/7 = 0.(142857)
2/2 = 1.0
3/8 = 0.375
45/56 = 0.803(571428)
解题思路:除法模拟,并求出不循环位数(分成2,5的指数,取指数的最大值)
code:
#include
#include
const int size=200000;
int aa[size],t[50];
char an[size];
bool f[100001];
int main()
{
int a,b,temp,m,t1,t2,i,j,len,l;
while(scanf("%d%d",&a,&b)!=EOF)
{
if(a%b==0)
{printf("%d.0\n",a/b);continue;}
temp=a/b;
if(temp==0)
{
t[0]=1;t[1]=0;
}
else
{
t[0]=0;
while(temp)
{t[++t[0]]=temp%10;temp/=10;}
//逆置
for(i=1;i<=t[0]/2;i++)
{temp=t[i];t[i]=t[t[0]-i+1];t[t[0]-i+1]=temp;}
}
temp=b;t1=t2=0;
while(temp%2==0){t1++;temp/=2;}
while(temp%5==0){t2++;temp/=5;}
//非循环的
m=t1>t2?t1:t2;
memset(f,0,sizeof(f));
temp=a%b;len=0;
f[temp]=1;
while(1)
{
temp=temp*10;
aa[++len]=temp/b;
temp%=b;
if(f[temp])break;
f[temp]=1;
if(temp==0)break;
}
l=0;
for(i=1;i<=t[0];i++)
an[++l]=t[i]+'0';
an[++l]='.';
for(i=1;i<=m;i++)
an[++l]=aa[i]+'0';
if(i<=len)
{
an[++l]='(';
for(;i<=len;i++)
an[++l]=aa[i]+'0';
an[++l]=')';
}
for(i=1;i<=l;i++)
{
printf("%c",an[i]);
if(i%76==0) printf("\n");
}
if(l%76!=0)printf("\n");
}
}
/*
------- test 1 -------
22 5
------- test 2 -------
1 7
------- test 3 -------
100000 59
------- test 4 -------
1 100000
------- test 5 -------
3 3
------- test 6 -------
59 330
------- test 7 -------
100000 9817
------- test 8 -------
1 99991
------- test 9 -------
982 4885
*/