识别数组在C++中的最小索引位置

identifying smallest index position of array in C++

本文关键字:索引 位置 数组 C++ 识别      更新时间:2023-10-16

我是新来的。 我搜索了现有问题以寻找这个问题的答案,它确实帮助我进步,但我拥有的代码仍然返回"0"而不是数组中最小值索引中的实际位置。

任何帮助将不胜感激,谢谢。

#include<iostream>
using namespace std;
int smallestIndex(int arr[], int size);
int main()
{
    int arr[6] = {500, 29, 36, 4, 587, 624};

    cout << "Index position for smallest element in array: " 
    << smallestIndex(arr, 6) << endl;
    return 0;
}
int smallestIndex(int arr[], int size)
{
    int temp;
    int n = arr[0];
        for (int i = 0; i > size; i++)
        {
            if (arr[i] < n)
                n = arr[i];
                temp = i;
        }
    return temp;
}
  • 条件i > size是错误的。应该是i < size.
  • 不要忘记初始化temp。将其写为 int temp = 0;,因为 n 的初始值是数组的第 0 个元素。
  • 您忘记使用块,temp的值将是错误的。

固定代码:

int smallestIndex(int arr[], int size)
{
    int temp = 0;
    int n = arr[0];
        for (int i = 0; i < size; i++)
        {
            if (arr[i] < n)
            {
                n = arr[i];
                temp = i;
            }
        }
    return temp;
}