模拟除法运算,利用数组ch[]保存商值,使用post[n]表示余数n除以d的商出现在ch[]中的位置(未出现过为-1),不必再每次对出现的商s进行检测,节约大量时间。循环进行除法运算,如果余数n出现过即为循环小数,n为零则为有限非循环小数。然后均终止除法运算,按照要求输出结果即可。
/*
ID:jzzlee1
PROB:fracdec
LANG:C++
*/
//#include <iostream>
#include<fstream>
#include<cstring>
using namespace std;
ifstream cin("fracdec.in");
ofstream cout("fracdec.out");
int e,t;
int post[100001];
char ch[100010];
void cal(int a)
{
int i=0;
do
{
i++;
a=a/10;
}
while(a);
i=i+2;;
e=t=i;
}
int main()
{
int i,n,d,a,s,flag=0,count=0;
cin>>n>>d;
if(n%d==0)//整除
cout<<n/d<<".0"<<endl;
else
{
memset(post,-1,sizeof(post));
a=n/d;n%=d;
cal(a);
while(1)
{
if(n==0)
{
flag=1;
break;
}
if(post[n]==-1)
{
post[n]=t++;
s=10*n/d;
ch[post[n]]=s+'0';
n=10*n%d;
}
else
{
flag=2;
break;
}
}
cout<<a<<".";
if(flag==1)
{
for(i=e;i!=t;i++)
{
cout<<ch[i];
if(i%76==0)
cout<<endl;
}
if((t-1)%76!=0)
cout<<endl;
}
else if(flag==2)
{
for(i=e;i<post[n];++i)
{
cout<<ch[i];
if(i%76==0)
cout<<endl;
}
cout<<'(';
i++;
if(i%76==0)
cout<<endl;
t++;
for(;i<t;++i)
{
cout<<ch[i-1];
if(i%76==0)
cout<<endl;
}
cout<<')';
cout<<endl;
}
}
return 0;
}