80分求助

P1422 小玉家的电费

KingRan @ 2024-01-02 19:58:38

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    double sum;
    cin >> n;
    if (n <= 150)
    {
        sum = n * 0.4463;
    }

    if (n >= 151 && n <= 400)
    {
        sum = (n - 150) * 0.4663 + 150 * 0.4463;
    }
    else
    {
        sum = (n - 400) * 0.5663 + 150 * 0.4463 + (400 - 151 + 1) * 0.4663;
    }
    cout << fixed << setprecision(1) << sum;

    return 0;
}

by KingRan @ 2024-01-02 20:00:45

第3组数据WA了
实在没看出来哪里的问题


by lpk1118 @ 2024-01-02 20:13:12

@KingRan 当n<=150时,第二个判断中给sum赋的值会取代第一个判断中赋的值


by chenyyegg @ 2024-01-02 20:30:57

cin >> n;
    if (n <= 150)
    {
        sum = n * 0.4463;
    }

    if (n >= 151 && n <= 400)
    {
        sum = (n - 150) * 0.4663 + 150 * 0.4463;
    }
    else
    {
        sum = (n - 400) * 0.5663 + 150 * 0.4463 + (400 - 151 + 1) * 0.4663;
    }

改为:

cin >> n;
    if (n <= 150)
    {
        sum = n * 0.4463;
    }

    else if (n >= 151 && n <= 400)
    {
        sum = (n - 150) * 0.4663 + 150 * 0.4463;
    }
    else
    {
        sum = (n - 400) * 0.5663 + 150 * 0.4463 + (400 - 151 + 1) * 0.4663;
    }

by KingRan @ 2024-01-02 20:45:06

@chenyyegg
我天,感谢感谢


|