描述
写一个程序,输入一个形如N/D的分数(N是分子,D是分母),输出它的小数形式。如果小数有循环节的话,把循环节放在一对圆括号中。
例如,
1/3 =0.33333333 写成0.(3),
41/333 = 0.123123123... 写成0.(123),
用xxx.0 等表示整数。
典型的转化例子:
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)
SAMPLE INPUT
45 56
SAMPLE OUTPUT
0.803(571428)
当某个余数第二次出现时,则循环节为该余数第一次出现至第二次出现之前
/*
ID: your_id_here
PROG: fracdec
LANG: C++
*/
#include <cstdio>
#include <algorithm>
using namespace std;
int n,d,cnt=0,nn,c;
int pos[1000005]={1},num[100005];//pos大小为分母的十倍,防止类似 1 99999 这样的数据出现而越界;最多有100000个不同的数,则num大小为100005
void cal() {
while(pos[n]==0) {
pos[n]=++cnt;
n*=10;
num[cnt]=n/d;
n%=d;
}
}
int main() {
freopen("fracdec.in","r",stdin);
freopen("fracdec.out","w",stdout);
scanf("%d%d",&n,&d);
n/=c=__gcd(n,d);
d/=c;
if(n%d==0) {
printf("%d.0\n",n/d);
return 0;
}
printf("%d.",nn=n/d);
c=1;
do {//计算已经输出的字符数
++c;
nn/=10;
}while(nn);
n=n%d;
cal();
pos[0]=0;
for(int i=1;i<=cnt;++i) {
if(i==pos[n]) {
printf("(");
if(++c==76)
printf("\n");
}
printf("%d",num[i]);
if(++c==76) {
c=0;
printf("\n");
}
}
if(n!=0)
printf(")");
printf("\n");
return 0;
}