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
相关产品推荐
相关产品推荐

