C++程序获取数组最小值索引失败:始终返回0求助
问题分析与解决方案
我来帮你定位一下问题,你的代码主要有两个小问题导致最小值的索引始终是0:
1. 索引初始化错误
在find_smallest函数里,你错误地把index初始化为myvector[0](数组第一个元素的值),而正确的初始索引应该是0(第一个元素的位置)。
2. 参数传递方式错误
C++中默认是值传递,你把index作为普通参数传给find_smallest函数时,函数内部修改的只是index的副本,不会影响main函数里的原始index变量。要让函数能修改外部变量,需要用引用传递(在参数前加&)。
修改后的完整代码
#include <iostream> using namespace std; // 修改参数:index使用引用传递,同时修正初始化逻辑 int find_smallest(int myvector[], int& index) { int smallest = myvector[0]; index = 0; // 初始索引设为0 for(int i = 0; i < 4; i++) { if(myvector[i] < smallest) { smallest = myvector[i]; index = i; } } return smallest; } int find_largest(int myvector[]) { int largest = myvector[0]; for(int i = 0; i < 4; i++) { if(myvector[i] > largest) { largest = myvector[i]; } } return largest; } // 简化sub_minmax函数,不需要多余参数 int sub_minmax(int largest, int smallest) { return largest - smallest; } int main() { int myvector[200], smallest, largest, subtraction, index; for(int i = 0; i < 4; i++) { cout << "Enter the number " << i+1 << endl; cin >> myvector[i]; } smallest = find_smallest(myvector, index); // 现在index会被函数修改 largest = find_largest(myvector); subtraction = sub_minmax(largest, smallest); cout << endl; cout << "The smallest number is: " << smallest << " at index " << index << endl; cout << "The largest number is: " << largest << endl; cout << "Their subtraction is: " << subtraction << endl; return 0; }
额外优化说明
- 我简化了
sub_minmax函数,它只需要最大值和最小值两个参数就能计算差值,不需要传入数组和多余的变量。 - 移除了不需要的
stdlib.h和stdio.h头文件,因为iostream已经满足需求。
测试你给出的示例输入40,250,9,50,程序会输出预期结果:
The smallest number is: 9 at index 2
The largest number is: 250
Their subtraction is: 241
内容的提问来源于stack exchange,提问作者alex108
相关产品推荐
相关产品推荐

