Description
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)
A single line with two space separated integers, N and D, 1 <= N,D <= 100000.
The decimal expansion, as detailed above. If the expansion exceeds 76 characters in length, print it on multiple lines with 76 characters per line.
45 56
0.803(571428)
这个题目意思就是让你把一个分数写成小数的形式并且如果是循环小数把循环节表示出来。
首先任何一个形如N/D 的分数,(N和D是整数,D非零) 一定可以表示成一个有限(或者有限循环)小数,证明可以百度。
有了上面的结论我们就可以大胆的除法一路除下去了,此题只需要按照笔算除法的方式进行,如果除尽了 那么商就是答案,如果是循环小数则答案中首次出现两次的相同的余数间一段数构成循环节,连同循环节前面的数一同构成答案。输出格式注意下就OK了
#include<stdio.h>
#define maxn 100005
int f[maxn],len;
int ans[maxn];
void outln()
{
if(len%76==0)
printf("\n");
}
int main()
{
int n,d,num;
scanf("%d%d",&n,&d);
ans[0]=n/d;
n%=d;
f[n]=1;
n*=10;
printf("%d.",ans[0]);
if(ans[0]<10)len=2;
else if(ans[0]<100)len=3;
else if(ans[0]<1000)len=4;
else if(ans[0]<10000)len=5;
else len=6;
num=2;
while(true)
{
if(n==0)
{
for(int i=2;i<num;i++)
{
outln();
printf("%d",ans[i]);
len++;
}
if(num==2)
printf("0");
break;
}
ans[num]=n/d;
n%=d;
if(f[n]!=0)
{
if(f[n]<2){printf("(");len++;}
for(int i=2;i<=num;i++)
{
outln();
printf("%d",ans[i]);
len++;
if(i==f[n])
{
outln();
printf("(");
len++;
}
}
outln();
printf(")");
break;
}
f[n]=num++;
n*=10;
}
return 0;
}