题目二:
http://topic.csdn.net/t/20051128/09/4422199.html
完成如下函数,给定分子和分母,输出其小数表示形式,循环节用[]表示,例如给出分子
:13,分母19,输出为:0.[13]
Answer1:
http://topic.csdn.net/t/20051128/09/4422199.html
13/19循环得太长了,基本上算不出来,楼上的解似乎也不对,我给出我的算法:
你可以上http://spaces.msn.com/members/yovn/看该算法的解释!
/********************************************
*
*Author:Yovn
*email:yovnchine@163.com
*
*********************************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define MINI_D 0.0000000001
int main(int argc,char** argv)
{
long num1;
long num2;
long integerPart=0;
long infinitePart=0;
long maxFactor=-1;
if(argc<3)
{
printf("usage: Dis n1 n2/n");
return ;
}
num1=atol(argv[1]);
num2=atol(argv[2]);
if(num2<=0||num1<=0)
{
printf("error,must be positive/n");
return;
}
if(num1%num2==0)
{
printf("find,%d/n",num1/num2);
return;
}
if(num1>num2)
{
integerPart=num1/num2;
num1=num1-integerPart*num2;
}
if(num1>1)
{
int i=2;
for(;i<=num1;i++)
{
if((num1%i)==0&&(num2%i)==0)
{
maxFactor=i;
}
}
if(maxFactor!=-1)
{
num1=num1/maxFactor;
num2=num2/maxFactor;
}
}
double temp1=(double)num1;
int p2=0,p5=0;
while((num2%2)==0)
{
num2/=2;
temp1/=2;
p2++;
}
while((num2%5)==0)
{
num2/=5;
temp1/=5;
p5++;
}
int max=p2>p5?p2:p5;
infinitePart=temp1*pow(10,max);
if(num2==1)
{
printf("find,%#8d.%.*d/n",integerPart,max, infinitePart);
return;
}
int k=1;
for(;;k++)
{
if(((int)(pow(10,k)-1)%num2)==0)
{
break;
}
}
int n=(pow(10,k)-1)/num2;
temp1*=n;
long integerP2=(long)temp1;
double tempInfinite=(temp1-integerP2)*pow(10,k);
tempInfinite+=integerP2;
long tempInteger=integerP2;
int inum=k;
while(tempInfinite-(long)(tempInfinite+MINI_D)>MINI_D)
{
integerP2=integerP2*pow(10,k)+(long)tempInfinite;
tempInfinite=(tempInfinite-(long)tempInfinite)*pow(10,k)+(long)tempInfinite;
inum+=k;
}
infinitePart=(long)(tempInfinite+MINI_D);
printf("find,%#8d.%.*d[%.*d]/n",integerPart,inum,integerP2,k, infinitePart);
return;