题目大意是,输入两个整数 a 和 b ,要求输出 a/b 的循环小数表示以及循环节的长度。
这道题实际上就是用两个数组模拟了一个做除法的过程,qot[] 用来保存每一次相除所得的商(quotient),rmd[] 用来保存每一次相除所得的余数(remainder),若要找到循环节,就只需要每做一次除法时,都遍历一遍两个数组中已经保存的元素,若本次计算所得的 qot 和 rmd 同时与之前保存过的 qot 和 rmd 相同,则可以得出循环节的长度及位置。最后注意格式输出即可。
代码如下:
#include <cstdio>
#include <cstring>
using namespace std;
int qot[3500], rmd[3500];
int main()
{
int a, b;
while(scanf("%d %d", &a, &b) == 2){
int m = 0, n = 0;
memset(qot, 0, sizeof(qot));
memset(rmd, 0, sizeof(rmd));
qot[0] = a / b;
rmd[0] = a % b;
for(int i = 1; ; i++){
qot[i] = rmd[i-1] * 10 / b;
rmd[i] = rmd[i-1] *10 % b;
for(int j = 1; j < i; j++){
if(qot[j] == qot[i] && rmd[j] == rmd[i]){
m = i; // m 用来保存循环节的末端位置
n = j; // n 用来保存循环节的起始位置
break;
}
}
if(n) break;
}
printf("%d/%d = %d.", a, b, qot[0]);
for(int i = 1; i < n && i <= 50; i++)
printf("%d", qot[i]);
printf("(");
for(int i = n; i < m && i <= 50; i++)
printf("%d", qot[i]);
if(m > 50) printf("...");
printf(")\n");
printf(" %d = number of digits in repeating cycle\n\n", m-n);
}
return 0;
}