所以我遇到了一些麻烦。我必须创建一个函数来找到数组中的最小数字。我知道一种方法,使用过多的 if/else if,如果数组大小发生变化,这不会有任何好处。我知道使用 for 循环应该可以解决问题,但我不知道如何编写它。任何朝着正确方向的插入将不胜感激。
#include <iostream>
using namespace std;
int findLowest(int[]);
int main()
{
int AR[5] = {4, 87, 1, -3, 78};
cout << findLowest(AR);
return 0;
}
int findLowest(int AR[])
{
return lowest;
}
最佳答案
如果您可以更改函数签名并包含一个指定一般限制的头文件,您可以执行以下操作,一次读取整个数组:
#include <climits>
...
/* assumes AR_size > 0 */
int findLowest(int AR[], int AR_size)
{
int lowest = INT_MAX;
for (i = 0; i < AR_size; ++i) {
lowest = (AR[i] < lowest) ? AR[i] : lowest;
}
return lowest;
}
关于c++ - 查找数组中的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33225740/