大佬们打扰了:哪里错了?

P5719 【深基4.例3】分类平均

Linda_rdfzEDP @ 2020-11-27 17:13:33

#include <iostream>
#include <cstdio>
using namespace std;
int main() {
    int n, k;
    scanf("%d %d", &n, &k);
    int ans1 = 0, num1 = 0, ans2 = 0, num2 = 0;
    for (int i = 1; i <= n; i++) {
        if (i % k == 0) {
            ans1 += i;
            num1++;
        } else {
            ans2 += i;
            num2++; 
        }
    }
    printf("%.1f ", double(ans1/num1)); 
    printf("%.1f\n", double(ans2/num2));
    return 0;
} 

只有40分


by pidan @ 2020-11-27 17:24:10

在输出的double后面加个1.0*


by pidan @ 2020-11-27 17:25:26

@Linda_rdfzEDP


by lxgw @ 2020-11-27 17:28:43

(ans1/num1)
(ans2/num2)

这两行语句还是整数的除法(整除),除完后的结果再转 double 类型,所以会错。

应改成

printf("%.1f ", double((ans1+0.0)/(num1+0.0))); 
    printf("%.1f\n", double((ans2+0.0)/(num2+0.0)));

加 0.0 是为了把整型转为浮点型


by Linda_rdfzEDP @ 2020-11-27 17:33:30

谢谢两位,讲的非常清楚%%%%%


|