USACO-Section 2.4 Fractions to Decimals(模拟)

58 篇文章 0 订阅

描述

写一个程序,输入一个形如N/D的分数(N是分子,D是分母),输出它的小数形式。如果小数有循环节的话,把循环节放在一对圆括号中。

例如,

1/3 =0.33333333 写成0.(3),

41/333 = 0.123123123... 写成0.(123),

用xxx.0 等表示整数。

典型的转化例子:

1/3 = 0.(3)
22/5 = 4.4
1/7 = 0.(142857)
2/2 = 1.0
3/8 = 0.375
45/56 = 0.803(571428)

SAMPLE INPUT

45 56

SAMPLE OUTPUT

0.803(571428)

当某个余数第二次出现时,则循环节为该余数第一次出现至第二次出现之前


/*
ID: your_id_here
PROG: fracdec
LANG: C++
*/
#include <cstdio>
#include <algorithm>

using namespace std;

int n,d,cnt=0,nn,c;
int pos[1000005]={1},num[100005];//pos大小为分母的十倍,防止类似 1 99999 这样的数据出现而越界;最多有100000个不同的数,则num大小为100005

void cal() {
    while(pos[n]==0) {
        pos[n]=++cnt;
        n*=10;
        num[cnt]=n/d;
        n%=d;
    }
}

int main() {
    freopen("fracdec.in","r",stdin);
    freopen("fracdec.out","w",stdout);
    scanf("%d%d",&n,&d);
    n/=c=__gcd(n,d);
    d/=c;
    if(n%d==0) {
        printf("%d.0\n",n/d);
        return 0;
    }
    printf("%d.",nn=n/d);
    c=1;
    do {//计算已经输出的字符数
        ++c;
        nn/=10;
    }while(nn);
    n=n%d;
    cal();
    pos[0]=0;
    for(int i=1;i<=cnt;++i) {
        if(i==pos[n]) {
            printf("(");
            if(++c==76)
                printf("\n");
        }
        printf("%d",num[i]);
        if(++c==76) {
            c=0;
            printf("\n");
        }
    }
    if(n!=0)
        printf(")");
    printf("\n");
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值