如何基于重量和距离在C++程序中计算包裹运输费用
C++包裹运费计算实现方案
计算逻辑拆解
- 第一步:根据包裹重量匹配单位费率
- ≤2kg:对应
twoOrLess常量1.10美元/500英里 - 2kg<重量≤6kg:对应
twoToSix常量2.20美元/500英里 - 6kg<重量≤10kg:对应
sixToTen常量3.70美元/500英里 - 10kg<重量≤20kg:对应
tenToTwenty常量4.80美元/500英里
- ≤2kg:对应
- 第二步:计算计费距离段数
规则为不足500英里按500英里计算,可通过整数运算向上取整实现:(int)(distance + 499) / 500,不需要额外调用数学库函数 - 第三步:总运费 = 单位费率 × 计费段数
完整修正代码
首先需要引入<iomanip>头文件用于格式化金额输出,同时修正原代码中重量校验条件错误、距离超3000无提示、拼写错误等问题:
#include <iostream> #include <iomanip> using std::cout; using std::cin; using std::endl; using std::fixed; using std::setprecision; double weight, distance; const double twoOrLess = 1.10; const double twoToSix = 2.20; const double sixToTen = 3.70; const double tenToTwenty = 4.80; int main() { cout << "Welcome to Shippers R Us!" << endl << "------------------------" << endl; // 全局设置金额输出保留2位小数 cout << fixed << setprecision(2); do { cout << "Package weight(in Kg, 0 to end): "; cin >> weight; while (weight < 0 || weight > 20) { if (weight == 0) { break; } else if (weight < 0) { cout << "weight must be greater than zero." << endl; cout << "------------------------" << endl; cout << "Package weight(in Kg, 0 to end): "; cin >> weight; } else if (weight > 20) { cout << "We do not ship items weighing more than 20 kilograms." << endl; cout << "------------------------" << endl; cout << "Package weight(in Kg, 0 to end): "; cin >> weight; } } if (weight == 0) { break; } cout << "Distance(in miles): "; cin >> distance; while (distance < 10 || distance > 3000) { cout << "Distance must be between 10 and 3,000 miles." << endl << "Distance(in miles): "; cin >> distance; } // 运费计算逻辑 double rate; if (weight <= 2) { rate = twoOrLess; } else if (weight <= 6) { rate = twoToSix; } else if (weight <= 10) { rate = sixToTen; } else { rate = tenToTwenty; } int segments = (int)(distance + 499) / 500; double shippingCost = rate * segments; // 输出结果 cout << "Shipping cost: $" << shippingCost << endl; cout << "------------------------" << endl; } while (weight != 0); return 0; }
关键逻辑说明
- 重量匹配用多分支
if-else判断,因为区间是连续的,前面的条件已经排除了更小的重量,所以后续判断不需要再写下限 - 向上取整计算段数的逻辑:给距离加499后截断整数部分再除以500,刚好实现不足500进1的需求,例如499英里得到1段,500英里得到1段,501英里得到2段,完全符合计费规则
- 用
fixed和setprecision(2)确保输出金额始终保留两位小数,符合货币显示习惯
内容的提问来源于stack exchange,提问作者SamXeox
相关产品推荐
相关产品推荐

