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

C++ do-while循环中变量赋值后值未更新原因排查

代码异常成因拆解
  • 整数运算截断导致人口值完全不增长
    所有参与人口、增长率计算的变量全是int整型类型,计算town_A_Growth / 100时是两个整数直接相除,结果会直接丢弃小数部分。比如增长率是3%,3/100的整数运算结果是0,整个增长公式就简化为town_A_Pop * (1 + 0),赋值回来的结果和原人口值完全相等——这就是为什么你在循环里写了赋值逻辑,却发现值根本没变化的核心原因。
  • 循环判断的变量名拼写错误
    C++语法严格区分大小写,代码里定义的城镇B人口变量是town_B_Pop(P大写),但do-while的循环终止条件里写的是town_B_pop(p小写)。如果代码能正常编译运行,大概率是其他位置定义过同名小写变量,会让循环判断的参考值完全偏离预期,无法在A人口超过B时正常终止循环。
  • 缺少标准输入输出依赖
    代码直接调用了cin、cout做输入输出,但没有引入<iostream>头文件,在严格遵循C++标准的编译环境下会直接报错,只有部分宽松的旧版本编译器能临时编译通过。

修正后的可运行参考代码

#include <iostream>
using namespace std;

int main() {
    // 改用浮点类型承载带小数的计算结果
    double town_A_Pop;
    double town_A_Growth;
    double town_B_Pop;
    double town_B_Growth;
    int years = 0;

    cout << "Enter the population of town A and of town B:" << endl;
    cin >> town_A_Pop >> town_B_Pop;
    cout << "Enter the growth rate of town A and of town B (%):" << endl;
    cin >> town_A_Growth >> town_B_Growth;

    do {
        // 除以100.0触发浮点运算,避免整数截断
        town_A_Pop = town_A_Pop * (1 + town_A_Growth / 100.0);
        cout << town_A_Pop << endl;
        town_B_Pop = town_B_Pop * (1 + town_B_Growth / 100.0);
        cout << town_B_Pop << endl;
        years++;
    // 修正变量名大小写匹配
    } while (town_A_Pop < town_B_Pop);

    cout << "It took " << years << " years for Town A to overtake Town B." << endl;
    cout << "Town A Population: " << town_A_Pop << endl;
    cout << "Town B Population: " << town_B_Pop << endl;

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 20:18:03