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)

題意:
給出兩個數(shù)N、D,求N除以D的結(jié)果。有循環(huán)小數(shù)的就將它們用圓括號括起來。如果能整除,要保留小數(shù)點后一位。

代碼如下:
/*
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出現(xiàn)過的位置。 
    if (!n)
    {
        s[i
++= '0';//如果n能被m整除,則小數(shù)點后保留一位 
    }
    
while (n)
    {
        n 
*= 10
        s[i
++= n / m + '0';
        n 
= n % m;
        
if (T[n])//如果n已經(jīng)出現(xiàn)過,則表明有循環(huán)小數(shù),標記出現(xià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);//將整數(shù)t轉(zhuǎn)化為字符存放在ch字符數(shù)組里。 
    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);//處理小數(shù)點以及小數(shù)點后的數(shù) 
    f = Turn(n, m);//處理小數(shù)點前面的數(shù) 
    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;      
}