C++使用for循环获取数组最小值运行结果异常问题求助
错误说明
你代码存在两处明显错误,共同导致最小值输出始终为13:
- 主函数调用
getLowest时传入的第二个参数错误,你误传了0,该参数需要传入数组的元素总个数4,才能让函数正常遍历所有数组元素。 getLowest的遍历循环逻辑完全写反:当前循环从下标0开始,判断条件为sub >= numElements,同时下标逐次递减,该循环无论传入什么正整数元素个数都不会执行,low变量永远保留初始赋值的数组第一个元素值13,因此输出结果固定。
修正后可正常运行代码
#include <iostream> using namespace std; int getHighest(int numArray[], int numElements); int getLowest(int numArray[], int numelements); int main() { int numbers[4] = { 13, 2, 40, 25 }; cout << "The highest number in the array is " << getHighest(numbers, 4) << "." << endl; // 修正:第二个参数改为数组元素个数4 cout << "The lowest number in the array is "<< getLowest(numbers,4) << "." << endl; return 0; } int getHighest(int numArray[], int numElements) { int high = numArray[0]; for (int sub = 1; sub < numElements; sub += 1) if (numArray[sub] > high) high = numArray[sub]; return high; } int getLowest(int numArray[], int numElements) { int low = numArray[0]; // 修正:循环逻辑调整为从下标1开始遍历到最后一个元素 for (int sub = 1; sub < numElements; sub++) if (numArray[sub]< low) low = numArray[sub]; return low; }
内容的提问来源于stack exchange,提问作者Colton Gil
相关产品推荐
相关产品推荐

