The decimal expansion of the fraction 1/33 is 0.03, where the 03 is used to indicate that the cycle 03repeats indefinitely with no intervening digits. In fact, the decimal expansion of every rational number(fraction) has a repeating cycle as opposed to decimal expansions of irrational numbers, which have nosuch repeating cycles.
Examples of decimal expansions of rational numbers and their repeating cycles are shown below.Here, we use parentheses to enclose the repeating cycle rather than place a bar over the cycle.
fraction decimal expansion repeating cycle cycle length
1/6 0.1(6) 6 1
5/7 0.(714285) 714285 6
1/250 0.004(0) 0 1
300/31 9.(677419354838709) 677419354838709 15
655/990 0.6(61) 61 2
Write a program that reads numerators and denominators of fractions and determines their repeatingcycles.For the purposes of this problem, define a repeating cycle of a fraction to be the first minimal lengthstring of digits to the right of the decimal that repeats indefinitely with no intervening digits. Thusfor example, the repeating cycle of the fraction 1/250 is 0, which begins at position 4 (as opposed to 0which begins at positions 1 or 2 and as opposed to 00 which begins at positions 1 or 4).InputEach line of the input file consists of an integer numerator, which is nonnegative, followed by an integerdenominator, which is positive. None of the input integers exceeds 3000. End-of-file indicates the endof input.
#include<stdio.h>
#include<string.h>
int a[5000],b[5000],c[5000];
int main(void)
{
int n,m,t;
while (~scanf("%d%d",&n,&m))
{
t=n;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
int count=0;
a[count++]=n/m;//将整数部分储存起来
n=n%m; //取余数
while(b[n]==0&&n!=0){
b[n]=count; //将余数在数组中的位置都标记出来,使循环次数t能在0<=t<m之中结束
c[count]=n; //将每次的循环都储存下来,之后可以方便确定循环起始位置
a[count++]=10*n/m; //将产生的循环小数记录下来
n=10*n%m; //产生出新的余数
}
printf("%d/%d = %d",t,m,a[0]);
printf(".");
for(int i=1;i<count&&i<=50;++ i) {
if (n!=0&&c[i]==n) printf("(");//利用储存下来的循环来计算循环开始的位置
printf("%d",a[i]);
}
if (n==0) printf("(0"); //没有循环小数,循环数记为0
if (count > 50) printf("...");
printf(")\n");
if(n!=0)
printf(" %d = number of digits in repeating cycle\n\n",count-b[n]);
else
printf(" %d = number of digits in repeating cycle\n\n",1);//一位循环数
}
return 0;
} //本题主要关键点有两点,其它要注意的是解题的规范性和细心
//1余数最多的数量顶多为m
//2将余数记录下来是找到循环开始是关键
本文介绍了一个程序设计问题:如何计算任意分数的十进制展开中循环节的长度,并提供了一个完整的C语言程序实现示例。

417

被折叠的 条评论
为什么被折叠?



