Fractions to Decimals
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)
题意:
给出两个数N、D,求N除以D的结果。有循环小数的就将它们用圆括号括起来。如果能整除,要保留小数点后一位。
代码如下:
/*
LANG: C
TASK: fracdec
*/
#include<stdio.h>
#define nmax 100000
char s[nmax], ch[nmax];
int T[nmax];
int Dic(int n, int m)
{
int i = 0, j, k = 0;
s[i++] = '.';
n = n % m;
T[n] = 1;//标记求模过程中n出现过的位置。
if (!n)
{
s[i++] = '0';//如果n能被m整除,则小数点后保留一位
}
while (n)
{
n *= 10;
s[i++] = n / m + '0';
n = n % m;
if (T[n])//如果n已经出现过,则表明有循环小数,标记出现过的位置,以便插入'('
{
k = T[n];
break;
}
T[n] = i;//所求的模是配对下一位的。模拟一下就清楚
}
s[i] = 0;
return k;
}
int Turn(int n, int m)
{
int i, t = n / m;
sprintf(ch, "%d", t);//将整数t转化为字符存放在ch字符数组里。
for (i = 0; ch[i] != 0; i++);
return i;
}
void Cat(int f, int k)
{
int i, sign = 1;
if (k)
{
for (i = 0; s[i] != 0; i++)
{
if (sign && i == k)
{
ch[f++] = '(';
i--;
sign = 0;
}
else
{
ch[f++] = s[i];
}
}
ch[f++] = ')';
ch[f] = 0;
}
else
{
for (i = 0; (ch[f] = s[i]) != 0; f++, i++);
}
}
int main()
{
freopen("fracdec.in", "r", stdin);
freopen("fracdec.out", "w", stdout);
int n, m, k, f, i;
scanf("%d%d", &n, &m);
k = Dic(n, m);//处理小数点以及小数点后的数
f = Turn(n, m);//处理小数点前面的数
Cat(f, k);//将两部分连接
for (i = 0; ch[i] != 0; i++)
{
printf("%c", ch[i]);
if ((i + 1) % 76 == 0)//每行不超过76个字符
{
printf("\n");
}
}
if (i % 76)
{
printf("\n");
}
fclose(stdin);
fclose(stdout);
//system("pause");
return 0;
}