查找数组最大最小元素的C++代码输出最小数为0是什么问题?
问题根因
你编写的代码存在数组越界访问错误:
- 查找最大/最小元素的循环终止条件写为了
i <= n,C++数组下标从0开始,你输入的n个元素仅存储在a[0] ~ a[n-1]的合法范围内,a[n]属于未初始化的内存空间,取值是随机不确定的。 - 你输入测试用例
{11,10,5,6,7}时n=5,循环会访问到a[5],这块内存刚好存储的数值为0,比数组内最小元素5更小,因此最终输出的最小元素变成了0。其他测试用例如果a[n]的随机值大于数组内所有元素,就不会影响最终结果,看起来表现“正常”。
修复方案
仅需要将查找循环的终止条件修改为i < n即可,修复后完整代码如下:
#include<bits/stdc++.h> using namespace std; int main() { int a[100000]; int large, small; int n; cin >> n; for (int j = 0; j < n; j++) { cin >> a[j]; } for (int j = 0; j < n; j++) { cout << a[j] << " "; } large = small = a[0]; // 修正循环边界 for (int i = 1; i < n; i++) { if (a[i] < small) { small = a[i]; } if (a[i] > large) { large = a[i]; } } cout << "Smallest is " << small << endl; cout << "Largest is " << large << endl; }
补充注意:如果业务场景存在输入n=0的可能,还需要额外对n=0的情况做判空处理,避免访问
a[0]时出现越界。
内容的提问来源于stack exchange,提问作者micro
相关产品推荐
相关产品推荐

