1102: 快递费[Delivery Fee]

1102: 快递费[Delivery Fee]

题目描述
圣诞节要到了,小知想给在外地的朋友寄一份礼物,于是来到快递公司询问价格。价格属于分段计价,如果重量不到5kg,则需要8元;如果重量不超过10kg且达到5kg,每公斤1.6元;如果重量超过10kg,每公斤1.5元。现在小知准备的礼物重量为a,请问小知需要付多少钱?(1<=a<=50)
输入
一个整数a,表示小知礼物的重量

输出
小知需要付的快递费用,保留一位小数

如果输入15输出就是15*1.5=22.5
但是我写的输出就是23.5

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int weight;
    cin >> weight;

    double cost;

    if (weight <= 5) {
        cost = 8.0;
    } else if (weight <= 10) {
        cost = 8.0 + (weight - 5) * 1.6;
    } else {
        cost = 8.0 + 5 * 1.6 + (weight - 10) * 1.5;
    }

    cout << setiosflags(ios::fixed) << setprecision(1) << cost << endl;

    return 0;
}

关键是题目怎么理解,是超出部分按照低费率,10kg以内按照1.6 还是说整体按照1.5
如果是后者,那么代码是

#include <iostream>
#include <iomanip>
using namespace std;
 
int main() {
    int weight;
    cin >> weight;
 
    double cost;
 
    if (weight <= 5) {
        cost = 8.0;
    } else if (weight <= 10) {
        cost = weight * 1.6;
    } else {
        cost = weight * 1.5;
    }
 
    cout << setiosflags(ios::fixed) << setprecision(1) << cost << endl;
 
    return 0;
}
 

【以下回答由 GPT 生成】

import math

weight = int(input())

cost = 0.0

if weight <= 5:
    cost = 8.0
elif weight <= 10:
    cost = 8.0 + (weight - 5) * 1.6
else:
    cost = 8.0 + 5 * 1.6 + (weight - 10) * 1.5

print("{:.1f}".format(cost))

修改后的代码如上所示,将输入的重量转换为整数后,根据重量的不同情况计算费用,并使用格式化字符串来保留一位小数输出结果。

在原有的C++代码上只需要删除头文件 #include <iomanip> 和命名空间 using namespace std;,然后将C++特有的输入输出语句 cin >> weight;cout << setiosflags(ios::fixed) << setprecision(1) << cost << endl; 替换为Python的输入输出语句即可。

修改后的代码可以正确输出小知需要支付的快递费用。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^