查找数组中的最小值

Finding smallest value in an array

本文关键字:最小值 数组 查找      更新时间:2023-10-16

我正试图编写一个函数来查找数组中的最小值,但我无法找出我所犯的错误。谁能帮我看一下吗?谢谢! !

void smallest(int array[],int size)
    {
        int smallest=array[0];
            for (int i=1;i<size-1;i++)
                {
                if (array[i]<smallest)
                 smallest=array[i];
                }
        cout<<smallest<<'n';
     }

代码没有执行,因为有断点,我看不出问题在哪里。

你可以在这里找到一个更有效的解决方案:
查找数组中最小值的最有效方法

代码片段:

int smallest = array[0];
for (int i = 0; i < array_length; i++) {
    if (array[i] < smallest) {
        smallest = array[i];
    }
}

你的循环不是指向数组的最后一个元素。你应该去掉条件的- 1。不要犹豫,测试接收到的参数的值:

void smallest(int array[], int size)
{
    if (size <= 0 || !array)
        return;
    int smallest = array[0];
    for (int i = 1; i < size ; i++)
        if (array[i] < smallest)
            smallest = array[i];
    cout << smallest << 'n';
}