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)
PROGRAM NAME: fracdec
INPUT FORMAT
A single line with two space separated integers, N and D, 1 <= N,D <= 100000.SAMPLE INPUT (file fracdec.in)
45 56
OUTPUT FORMAT
The decimal expansion, as detailed above. If the expansion exceeds 76 characters in length, print it on multiple lines with 76 characters per line.SAMPLE OUTPUT (file fracdec.out)
0.803(571428)
/*
ID: conicoc1
LANG: C
TASK: fracdec
*/
#include<stdio.h>
#include<string.h>
int N,D;
char str[100000];
int mod[1000000][2];
int i=0;
int j=0;
int flag;
int IntLength;
int count=0;
void itoa(int number)
{
if(number>9)
itoa(number/10);
str[i++]=number%10+'0';
}
int Search()
{
if(mod[N][0]==1)
return mod[N][1];
return -1;
}
int main()
{
FILE *fin,*fout;
fin=fopen("fracdec.in","r");
fout=fopen("fracdec.out","w");
memset(mod,0,sizeof(mod));
fscanf(fin,"%d %d",&N,&D);
itoa(N/D);
str[i++]='.';
IntLength=i;
do{
N=(N%D)*10;
if((flag=Search())!=-1)
break;
str[i++]=(N/D)+'0';
mod[N][0]=1;
mod[N][1]=j++;
}while(N%D!=0);
if(N%D==0)
fprintf(fout,"%s\n",str);
else{
for(j=0;j<i;j++){
if(j==(IntLength+flag)){
fprintf(fout,"(");
count++;
if(count%76==0)
fprintf(fout,"\n");
}
fprintf(fout,"%c",str[j]);
count++;
if(count%76==0)
fprintf(fout,"\n");
}
fprintf(fout,")\n");
}
return 0;
}
觉得自己每次做模拟的题目的时候,代码量都奇长无比。。还有各种纠结于输出或者小地方上的代码精简不了,应该都是基本功的问题
就像我最近在看K&R的The C Programming Language一样,如果让我自己写后缀算术表达式的计算,字符串,数字的相互转换,估计又是冗长的代码量
大牛不愧是大牛,几行代码就能看出编程的功力。
这道题是模拟除法,当被除数重复时算法结束,打印输出
一开始觉得是余数重复时才结束,可是有个测试数据 59, 330 会出现0.(178)的情况。。可以发现590和2900除以330的余数都是260.
最后不爽了把hash开到100万才AC掉。。