You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++新手求助:while循环未执行内部代码问题排查

问题排查:你的while循环未执行的原因及修复方案

嘿,作为编程新手遇到这种问题太正常了,咱们一步步拆解你的问题:

核心问题:错误使用了while循环

你的代码里用while循环来判断重量和距离的费用区间,但这里根本不需要循环——你只需要根据用户输入的重量/距离做一次条件判断,而不是重复执行判断逻辑。

为什么循环没执行?

看你的循环条件:

  • 重量循环:while (weight < MAX_POUNDS),而MAX_POUNDS是20.0。如果用户输入的重量≥20,这个条件直接不成立,循环内部代码完全不会运行,weightCharges就保持初始的0.0。
  • 距离循环同理:while (distance < MAX_DISTANCE),MAX_DISTANCE是500.0,输入距离≥500时循环直接跳过,distanceCharges也保持0.0。

更糟的是,就算用户输入的重量<20,进入循环后你没有修改weight的值,循环会一直重复执行,变成死循环!

修复方案:把while换成if判断

你需要的是单次条件分支判断,而不是循环。同时调整判断逻辑,先检查是否超出最大限制,再处理区间费用:

// 基于重量的费率
const double ZERO_TO_TEN_POUNDS = 0.75;
const double TEN_TO_FIFTEEN_POUNDS = 0.85;
const double FIFTEEN_TO_TWENTY_POUNDS = 0.95;
const double MAX_POUNDS = 20.0;
// 基于距离的费率
const double ZERO_TO_FIFTY_MILES = 0.07;
const double FIFTY_TO_ONEHUNDRED_MILES = 0.06;
const double ONEHUNDRED_TO_TWOHUNDRED_MILES = 0.05;
const double TWOHUNDRED_TO_FIVEHUNDRED_MILES = 0.04;
const double MAX_DISTANCE = 500.0;
double weight, distance, weightCharges = 0.0, distanceCharges = 0.0, total;
// 显示菜单并获取用户选择
cout << "Welcome to Marie's Shipping Company!\n\n";
cout << "Please enter the weight in pounds of your package: ";
cin >> weight;
cout << "Please enter the distance in miles to be shipped: ";
cin >> distance;
// 根据用户输入设置重量费用
if (weight <= MAX_POUNDS) {
    if (weight <= 10)
        weightCharges = weight * ZERO_TO_TEN_POUNDS;
    else if (weight <= 15)
        weightCharges = weight * TEN_TO_FIFTEEN_POUNDS;
    else // 15 < weight <=20
        weightCharges = weight * FIFTEEN_TO_TWENTY_POUNDS;
} else {
    cout << "Sorry. Packages over 20 pounds are not allowed.\n";
}
// 根据用户输入设置距离费用
if (distance <= MAX_DISTANCE) {
    if (distance <= 50)
        distanceCharges = distance * ZERO_TO_FIFTY_MILES;
    else if (distance <= 100)
        distanceCharges = distance * FIFTY_TO_ONEHUNDRED_MILES;
    else if (distance <= 200)
        distanceCharges = distance * ONEHUNDRED_TO_TWOHUNDRED_MILES;
    else // 200 < distance <=500
        distanceCharges = distance * TWOHUNDRED_TO_FIVEHUNDRED_MILES;
} else {
    cout << "Sorry. Packages are not allowed to be shipped over 500 miles.\n";
}
// 计算并显示总费用
if (weightCharges != 0 && distanceCharges !=0) {
    total = weightCharges + distanceCharges;
    cout << fixed << showpoint << setprecision(2);
    cout << "Your total charge is: $" << total << endl;
}
return 0;

额外优化点

我还加了一个判断:只有当重量和距离都符合要求时,才计算并显示总费用,避免在输入非法值时输出0.0的错误结果。

内容的提问来源于stack exchange,提问作者mphil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:47:43