94 分数化小数
作者: xxx时间限制: 1S章节: 字符串
问题描述 :
写一个程序,输入一个形如N/D的分数(N是分子,D是分母),输出它的小数形式。
如果小数有循环节的话,把循环节放在一对圆括号中。
例如, 1/3 = .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)
输入说明 :
单独的一行包括被空格分开的 N和D, 1 <= N,D <= 100000。
输出说明 :
小数的表示方法上面说的很明白了,如果输出的长度超过76个字符,每行输出76个字符(包括小数点、括号等)。
输入范例 :
45 56
输出范例 :
0.803(571428)
#include<stdio.h>
int tot=0,a[1000009],h[1000009],b[1000009];
void show(int a);
int main(){
int j=0,i=0,n,d,rt,m;
scanf("%d %d",&n,&d);
printf("%d",n/d);
printf(".");
//tot表示数的占位情况
rt=n/d;
if (rt==0)tot=1;
while (rt) {
tot++,rt=rt/10;
}
tot++;
//取余数
n=n%d;
//特殊情况判断
if (n==0)printf("0");
//下面循环就小数
while(n)//如果还有余数,也就是还能除的情况,就接着除
{
i++;
//如果b[n]==0,也就是n这个余数没有出现过的情况
if (b[n]==0){
b[n]=1;//将n这个余数置为出现
h[n]=i;//表示n这个余数出现的对应位置
}else{
j=h[n];//余数出现,说明找到了循环节
break;
}
n=n*10;
//a[i]里面存储的就是余数
a[i]=n/d;
n=n%d;//继续找余数
}
m=i;//m表示小数部分的个数+1
//如果找到循环节的位置
if (j){
//输出小数点后的非循环节
for (i=1;i<j;i++) show(a[i]);
printf("(");tot++;if (tot==76) printf("\n"),tot=0;
for (i=j;i<m;i++) show(a[i]);
printf(")");tot++;if (tot==76) printf("\n"),tot=0;
}else {
//每出现循环节,说明是整数
for (int i=1;i<=m;i++)show(a[i]);
}
return 0;
}
void show(int a){
printf("%d",a);
tot++;if (tot==76) tot=0,printf("\n");
}