UVA, 202 Repeating Decimals

    xiaoxiao2021-03-25  110

    Sample Input

    76 25

    5 43

    1 397

    Sample Output

    76/25 = 3.04(0) 1 = number of digits in repeating cycle 5/43 = 0.(116279069767441860465) 21 = number of digits in repeating cycle 1/397 = 0.(00251889168765743073047858942065491183879093198992...) 99 = number of digits in repeating cycle

    输入分子和分母,找出来循环的小数部分

    #include<cstdio>

    #include<cstring>

    #include<stack>

    #include<iostream>

    using namespace std;

    #define M 3000

    int main()

    {

    int a,b;

    a = b = 0;

    while(cin >> a >> b){//可以直接这样输入

    printf("%d/%d = %d.",a,b,a/b);

    int yushu[M] = {0},shang[M] = {0};

       ///     memset(shang, 0, 30);

    //取余数,求初值后,循环的来计算

    a %= b;

    a *= 10;

    for(int t = 0; t < M; t++) {

    shang[t] = a/b;

    a = a%b;

    yushu[t] = a;

    a *= 10;

    }

                       //判断从哪一位开始循环。很巧妙

    int i ,j;

    for(i = 0; i < M; i++){

    for(j = i + 1; j < M; j++) {

    if(((shang[j] == shang[i]) && (yushu[j] == yushu[i]) )|| (i >= 100)){

    goto a1;

    }

    }

    }

    a1:for(int m = 0; m < j; m++){

    if(m == i) printf("(");

    if(m<50) printf("%d",shang[m]);

    else {printf("..."); break;}

    }

    printf(")\n");

    printf("   %d = number of digits in repeating cycle\n\n",j-i);

    }

    return 0;

    }

    1 自己看了别人的代码,才学会了如何处理一个数的小数部分。模拟平时手算的步骤。

    2 跳出两个循环可以用goto 。不要用break

    3 发现提前定义一个变量M。这样就可以快速切换数组大小,方便debug

    4 赋值直接用 int yushu[M] = {0},shang[M] = {0} 。如果用memset 有时候会出错

    转载请注明原文地址: https://ju.6miu.com/read-8093.html

    最新回复(0)