2.5:分数化小数 个人解答

近日在刷紫皮书,练习题2.5书上没有答案,网上的答案在我看来大多是错的,这里自己写了一份,与大家分享。
网上的答案大多错在三点
一是 没有考虑c的取值范围为<=100,直接使用double类型相除。
二是 采用了竖式模拟,但是没有考虑四舍五入
三是 考虑了四舍五入却没考虑其带来的进位问题
上代码,请勘误。

#include<iostream&gt>
using namespace std;
int main()
{
    int a,b,c,cases,ans1,ans[100];
    while(true)
    {
        cin>>a>>b>>c;
        if(a==b&&a==c&&a==0)
            break;

        cases++;
        ans1=a/b;
        a=a%b;
        int i=0;
        for(i; i<c; i++)
        {
            a*=10;
            ans[i]=a/b;
            a=a%b;
        }
        if(a*10/b>=5)
        {
            bool flag=false;
            while(i--)
            {
                ans[i]++;
                if(ans[i]<10)
                {
                    flag=true;
                    break;
                }
                ans[i]=0;
            }
            if(!flag)
            {
                ans1++;
            }
        }
        cout<<"Case "<<cases<<": "<<ans1<<".";
        for(int j=0; j<c; j++)
        {
            cout<<ans[j];
        }
    }
    return 0;
}
点赞