40分求助

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

Flower_Bloom @ 2022-08-10 20:30:35

40分蒟蒻求助

2,3,4测试点WA

以下是代码

#include <bits/stdc++.h>
using namespace std;
int main()
{
    long long n, m, hn = 0, hbn = 0, sumn = 0,sumbn=0;
    double avern = 0, averbn = 0;
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        if (i % m == 0)
        {
            hn += i;
            sumn++;
        }
        if (i % m != 0)
        {
            hbn += i;
            sumbn++;
        }
    }
    avern = hn / sumn;
    averbn = hbn / sumbn;
    printf("%.1lf %.1lf", avern, averbn);
    return 0;
}

求助各位大佬


by IamZZ @ 2022-08-10 20:39:34

@Mant1e

#include <bits/stdc++.h>
using namespace std;
int main()
{
    long long n, m, hn = 0, hbn = 0, sumn = 0,sumbn=0;
    double avern = 0, averbn = 0;
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        if (i % m == 0)
        {
            hn += i;
            sumn++;
        }
        if (i % m != 0)
        {
            hbn += i;
            sumbn++;
        }
    }
    avern = hn * 1.0 / sumn;
    averbn = hbn * 1.0 / sumbn;
    printf("%.1lf %.1lf", avern, averbn);
    return 0;
}

再试试


by Flower_Bloom @ 2022-08-10 20:45:08

@oier_lyb 谢谢!已经AC了 可是为什么会这样呢


by IamZZ @ 2022-08-10 21:01:22

嗯,因为hn和hbn是long long

进行除法是会以整数返回,强制转成double就可以了

*1.0或在前面加上(double)都可以


by Flower_Bloom @ 2022-08-10 21:20:54

哦,谢谢大佬


|