Repeating Decimals

Repeating Decimals

题目链接:https://vjudge.net/contest/332906#problem/A

题意:

给出一个分数的分子和分母,计算其所得小数及小数循环体的长度,循环体要用()括起,如果循环体长度大于50,只输出请五十个数后加”…“,并按要求输出。


以1 / 7为例:

​ 商 余数

1/7 0 1

10/7 1 3

30/7 4 2

20/7 2 6

60/7 8 4

40/7 5 5

50/7 7 1

10/7 1 3

不断地用余数*10再除以除数,,并将每次的上保存下来,如果第一次循环体结束,下一次循环体开始,则第二次循环的第一个商和余数一定与第一次循环的第一个的相同。

用两个数组分别存每一次的商和余数,每算一次循环查找一次,找到就记录循环体的起点和终点并break。

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<string>
#include<map>
using namespace std;
int s[3005],y[3005];

int main()
{
    int a,b;
    while(scanf("%d%d",&a,&b)!=EOF){
        int temp=a,be,ed,flag=0;
        for(int i=0;;i++){
            s[i]=temp/b;
            y[i]=temp%b;
            for(int j=1;j<i;j++){  //i=0的时候是小数的整数部分,这里循环应从j=1开始
                if(s[i]==s[j] && y[i]==y[j]){
                    be=j;
                    ed=i;
                    flag=1;
                    break;
                }
            }
            if(flag==1) break;
            temp=(temp%b)*10;
        }
        cout<<a<<"/"<<b<<" = "<<s[0]<<".";
        for(int i=1;i<be;i++) cout<<s[i];
        cout<<"(";
        if(ed-be>50){
            for(int i=be;i<be+50;i++) cout<<s[i];
            cout<<"...";
        }
        else{
            for(int i=be;i<=ed-1;i++) cout<<s[i];
        }
        cout<<")"<<endl;
        cout<<"   "<<ed-be<<" = number of digits in repeating cycle"<<endl;
        cout<<endl;

    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值