WHCSRL 技术网

2021-10-31【习题 2-5 分数化小数 (decimal)(C++语言版)】_eternity

题目描述:

输入正整数a,b,c,输出a/b的小数形式,精确到小数点后c位,a,b<=10^6,c<=100
输入包含多组数据,结束标志为a=0,b=0,c=0;

Input:

1 6 4
0 0 0
  • 1
  • 2

Output:

Case1: 0.1667
  • 1

程序:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;

const int inf=0x3f3f3f3f;
const int maxn=1e6+5;
void solve(){
    int a, b, c;
    int cnt = 0;
    while(scanf("%%d%%d%%d",&a,&b,&c)&&(a||b||c)){
        cnt++;
        printf("Case%%d:%%.*lf
",cnt, c, 1.0 * a / b);
        
        // 小数点.后“*”表示输出位数,具体的数据来自参数表
        // printf格式字符串中,与宽度控制和精度控制有关的常量都可以换成变量
        // 方法就是使用一个“*”代替那个常量,然后在后面提供变量给“*”。
    }
}

int main(){
    solve();
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

input:

1 3 100
1 6 4
0 0 0
  • 1
  • 2
  • 3

output:

Case: 1: 0.3333333333333333148296162562473909929394721984863281250000000000000000000000000000000000000000000000000000000000000000 
Case: 2: 0.1667
  • 1
  • 2

错误原因:double的有效精度只有16位。

AC代码:

#include<bits/stdc++.h>
using namespace std;
void solve(){

    int a,b,c,kase = 0;
    while (~scanf("%%d%%d%%d", &a, &b, &c))
    {
        if (!a && !b && !c) break;
        kase++;
        //先输出小数点前的数字
        printf("Case: %%d: %%d.", kase, a/b);
        a %%= b;
        //输出小数点后的c-1位
        for (int i = 0; i < c-1; ++i) 
        {
            a *= 10;
            printf("%%d", a/b);
            a %%= b; //跳出时a为c-1位运算后的余数
        }
        //考虑最后一位四舍五入
        int more = ((a*10)%%b * 10) / b; //观察第c位的后一位
        if (more >= 5)
            printf("%%d
", (a*10)/b + 1);
        else printf("%%d
", (a*10)/b);
    }
}
int main(){
    solve();
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

input:

1 3 100
1 6 4
0 0 0
  • 1
  • 2
  • 3

output:

Case: 1: 0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
Case: 2: 0.1667
  • 1
  • 2
推荐阅读