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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:57:03