USACO Section 2.4 Fractions to Decimals

首先答案不可能是无限不循环小数,因为无限不循环小数不能用分数表示。

之所以出现循环是因为余数出现了重复,只需要用数组记录余数出现的位置,用判重来结束循环即可。

#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
#include <string>
#include <stack>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
/*
ID: kkkwjx1
PROG: fracdec
LANG: C++
*/
typedef long long LL;
const int maxn=100005;
int pos[maxn];
int main()
{
    freopen("fracdec.in","r",stdin);
    freopen("fracdec.out","w",stdout);
    int N,D;
    cin>>N>>D;
    memset(pos,-1,sizeof(pos));
    string str;
    bool flag=true;
    if((N<0&&D>0)||(N>0&&D<0))
        flag=false;
    char numb[30];
    sprintf(numb,"%d",N/D);
    str+=string(numb);
    int p=0;
    string dec;
    N%=D;
    if(N==0)
    {
        dec=".0";
    }
    else
    {
        while(N)
        {
            if(pos[N]!=-1)
            {

                dec.insert(pos[N]+1,"(");
                dec+=')';
                break;
            }
            if(p==0)
                dec+='.';
            pos[N]=p++;
            N*=10;
            dec+='0'+N/D;
            N%=D;
        }
    }
    str+=dec;
    if(str!="0"&&!flag)
        str.insert(0,"-");
    for(int i=0; i<str.size(); ++i)
    {

        cout<<str[i];
        if((i+1)%76==0||i==str.size()-1)
            cout<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值