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

C++如何在循环外打印for循环内部声明或赋值的变量

问题修复方案

你代码的问题出在两处:

  • 向量越界访问:第二个for循环的判断条件写为u <= pan_ate.size(),但C++中vector的下标取值范围是0 到 pan_ate.size()-1,同时你的判断逻辑里还访问了pan_ate[u+1],直接触发了数组越界,属于未定义行为,所以high变量的赋值结果不符合预期。
  • 最大值统计逻辑错误:原逻辑仅对比相邻两个元素的值,只能记录相邻两个元素中的较大值,无法遍历所有元素得到全局的最大值。
修复后代码

你可以直接遍历所有元素逐个比对得到最大值,修复后的代码如下:

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

int main() {
    cout << "\t****Pancakes****" << endl << endl;

    vector<int> pan_ate;

    int people;
    int high = 0;

    cout << "How many people ate pancakes: ";
    cin >> people;

    for(int i = 1; i <= people; i++) {
        int eat;
        cout << "How many pancakes did person " << i << " eat? ";
        cin >> eat;
        pan_ate.push_back(eat);
    }

    // 修复后的遍历逻辑
    for(int u = 0; u < pan_ate.size(); u++) {
        if(pan_ate[u] > high) {
            high = pan_ate[u];
        }
    }
    cout << "The highest amount of pancakes ate was: " << high;
    return 0;
}

修复后逻辑会逐个对比所有吃煎饼的数量,只要当前值比已记录的最大值high大就更新high,循环结束后high存储的就是全局最大值,循环边界u < pan_ate.size()也不会出现越界问题。

内容的提问来源于stack exchange,提问作者Cod Pod Tracks

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 17:42:02