Repeating Decimals

Uva202

这道题可以直接将值除出来就可以了,如果出现了余数相同就表示出现循环数了,

输出的时候需要注意一下。

#include <stdio.h>
#include <string.h>
#define clr( a ) memset ( a, 0, sizeof ( a ) )
const int maxn = 3005;
int ans[maxn], vis[maxn], s[maxn];
int main ( )
{
    int n, m, cnt;
    while ( ~ scanf ( "%d%d", &n, &m ) )
    {
        clr ( vis );    //vis标记每个数字出现在ans的位置
        clr ( s );  //保存上一个数的值
        cnt = 0;
        printf ( "%d/%d = %d.", n, m, n/m );
        ans[cnt ++] = n/m;  //保存除出来的值
        n = n%m;
        while ( n && vis[n] == 0 )  //余数为或余数前面出现过
        {
            vis[n] = cnt;   //标记n出现的位置
            s[cnt] = n; //保存ans[cnt]由n除出来的
            ans[cnt ++] = 10*n/m;
            n = n*10%m;
        }
        for ( int i = 1; i < cnt && i <= 50; i ++ )
        {
            if ( n && s[i] == n )   //当s[i]==n即循环的位置
                printf ( "(" );
            printf ( "%d", ans[i] );
        }
        if ( n == 0 )
            printf ( "(0" );
        if ( cnt > 50 )
            printf ( "..." );
        printf ( ")\n" );
        printf ( "   %d = number of digits in repeating cycle\n",  n == 0 ? 1 : cnt-vis[n] );
        //当n == 0时需要考虑,1/250时,长度是1
        printf ( "\n" );
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值