Repeating Decimals 【字符串处理+高精度】

求2数相除的循环表示形式,就是高精度+一下字符串的处理

需要注意一下 1/6 的时候是 0.1(6),循环位数为1,而不是2

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXD 3000 + 10
int vis[MAXD];
int main(){
    int n,m;
    while(scanf("%d%d",&n,&m) != EOF){
        int x = n , y = m;
        memset(vis,0,sizeof(vis));
        char str[MAXD];
        int t,ans,ok1 = 0,ok2 = 0,size = 0;
        int countx = 1;
        int cir = 50;
        int pos = 0;
        do{
            t = n % m;
            if(t == 0) {
                ok2 = 1;
                break;
            }
            if(vis[t]){
            countx = countx - vis[t];
            pos = vis[t];
            break;
            }
            else  vis[t] = countx;
            ans = 10 * t / m;
            if(size < 50)
            str[size++] = ans +'0';
            else if(size >= 50)
            ok1 = 1;
            n = 10 * t % m;
            countx++;
        }while(true);
        if(ok1){
            str[size++] = '.';
            str[size++] = '.';
            str[size++] = '.';
        }
        str[size] = '\0';
        if(ok2){
        printf("%d/%d = %d.%s(0)\n",x,y,x/y,str);
        printf("   1 = number of digits in repeating cycle\n");
        }
        else {
        printf("%d/%d = %d.",x,y,x/y);
        for(int i = 0 ; i < strlen(str); i++){
            if(i == pos - 1) printf("(");
            printf("%c",str[i]);
        }
        printf(")\n");
        printf("   %d = number of digits in repeating cycle\n",countx);
        }
        printf("\n");
    }
    return 0;
}


你可能感兴趣的:(Repeating Decimals 【字符串处理+高精度】)