使用函数从数组中索引最小值的问题

Problems with Indexing Minimum value from array using a function

本文关键字:索引 最小值 问题 数组 函数      更新时间:2023-10-16

因此,我们得到了一个涉及两个阵列(一个字符串,另一个包括值(的项目,我决定使用电影和数年。该项目的参数之一是显示最大值和最小值及其字符串。现在,最大功能正常,但是当我尝试运行最小值时,它说不是初始化的。我在做什么错?

#include <iostream>
#include <string>
using namespace std;
int avgYear(int arr[], int size);
int indexMin(int arr[], int size);
int indexMax(int arr[], int size);
int main()
{
    int total = 0;
    string name[] = {"Toy Story", "A Bug's Life", "Toy Story 2", "Monster's Inc.", "Finding Nemo", "The Incredibles", "Cars", "Ratatouille", "WALL-E", "Up"};
    int year[] = { 1995, 1998, 1999, 2001, 2003, 2004, 2006, 2007, 2008, 2009};
    for (int x = 0; x < 10; x++)
        cout << name[x] << "     " << year[x] << endl;
    cout << "The average year of release was " << avgYear(year, 10) << endl;
    cout << "The First Year of Release was " << name[indexMin(year, 10)] << " in " << year[indexMin(year, 10)] << endl;
    cout << "The Last Year of Release was "<< name[indexMax(year, 10)] << " in " << year[indexMax(year, 10)] << endl;

    return 0;
}
int avgYear(int arr[], int size)
{
    int avg;
    int total=0;
    for (int x = 0; x < size; x++)
        total += arr[x];
    avg = total / size;
    return avg;
}
int indexMin(int arr[], int size)
{
    int iMin;
    int min = arr[0];
    for (int x = 1; x < size; x++)
        if (arr[x] < min)
        {
            min = arr[0];
            iMin = x;
        }
    return iMin;
}
int indexMax(int arr[], int size)
{
    int iMax;
    int max = arr[0];
    for (int x = 0; x < size; x++)
        if (arr[x] > max)
        {
            max = arr[x];
            iMax = x;
        }
    return iMax;
}   

如果最小值为 arr[0],则iMin永远不会初始化,因为if (arr[x] < min)永远不会返回 true 。您的最大功能也有相同的问题,但由于最大元素不在索引0。

而起作用。
int iMin = 0;

应该解决您的问题。同样,最好养成始终初始化您的变量和字段的好主意。存储在非初始化变量中的值是不确定的,从中读取是不确定的行为。

如果您以这样的初始化年份:

int year[] = { 2009, 2008, 2007, 2006, 2004, 2003, 2001, 1999, 1998, 1995};

然后,最小工作正常,最大值是错误。^_^

您必须初始化imin和imax,而初始数字必须与ARR索引相同,例如:

// min
int nStartIndex = 0;
int iMin = nStartIndex;
int min = arr[nStartIndex];
// max
int nStartIndex = 0;
int iMax = nStartIndex;
int max = arr[nStartIndex];