关于循环小数的处理
问题描述:
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)
Input :
A single line with two space separated integers,N and D,1<=N,D<=100000.
Output :
The decimal expansion, as detailed above. If the expansion exceeds 76 characters in length, print it on multiple lines with 76 characters per line.
例子:
输入:45 56
输出:0.803(571428)
程序代码:
问题描述:
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)
Input :
A single line with two space separated integers,N and D,1<=N,D<=100000.
Output :
The decimal expansion, as detailed above. If the expansion exceeds 76 characters in length, print it on multiple lines with 76 characters per line.
例子:
输入:45 56
输出:0.803(571428)
程序代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <windows.h>
- #define LEN 100 //最大小数位数
- typedef struct _div
- {
- long int num; //分子
- long int den; //分母
- long int quot[LEN]; //商
- long int resi[LEN]; //余数
- unsigned long int cycle_point; //循环点
- unsigned long int length; //商的个数
- }DIV;
- void divide(DIV &tmp)
- {
- unsigned int len=0, i=0;
- ldiv_t result;
- if(!tmp.den)
- {
- printf("Denominator Error!/n");
- exit(1);
- }
- while(len<LEN)
- {
- result=ldiv(tmp.num ,tmp.den);
- tmp.quot[len]=result.quot;
- tmp.length+=1;
- if(result.rem!=0)
- {
- tmp.resi[len]=result.rem ;
- tmp.num=result.rem*10;
- while(i!=len)
- {
- if(tmp.resi[i]==result.rem)
- {
- tmp.cycle_point=i;
- return ;
- }
- i++;
- }
- }
- else
- return ;
- len++;
- i=0;
- }
- }
- int main()
- {
- DIV oper;
- unsigned int i=0, len=0 ,repair=0, flag=0;
- oper.length=0;
- printf(" 请输入分子(nume):");
- scanf("%ld",&oper.num);
- printf(" 请输入分母(demo):");
- scanf("%ld",&oper.den);
- divide(oper);
- printf("%ld%c",oper.quot[i++],'.');
- if(oper.length==1)
- printf("%d",0);
- else
- {
- while(i<oper.length)
- {
- if(i==oper.cycle_point+1)
- {
- printf("%c%ld",'(',oper.quot[i]);
- flag=1;
- }
- else
- printf("%ld",oper.quot[i]);
- i++;
- }
- if(flag)
- printf("%c",')');
- }
- printf("/n");
- return 0;
- }