【问题标题】:Problems with Indexing Minimum value from array using a function使用函数从数组中索引最小值的问题
【发布时间】:2017-10-01 22:59:22
【问题描述】:

所以我们得到了一个涉及两个数组(一个是字符串,另一个包含值)的项目,我决定使用电影和年份。该项目的参数之一是显示最大值和最小值及其字符串。现在,最大值工作正常,但是当我尝试运行最小值时,它说它没有初始化。我做错了什么?

#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;
}   

【问题讨论】:

    标签: c++ arrays function max min


    【解决方案1】:

    如果最小值是arr[0],那么iMin 将永远不会被初始化,因为if (arr[x] &lt; min) 永远不会返回true。 你的 max 函数也有同样的问题,但是因为 max 元素不在索引 0 处,所以可以工作。

    int iMin = 0;
    

    应该可以解决您的问题。此外,养成始终初始化变量和字段的习惯也是一个好主意。存储在未初始化变量中的值是不确定的,reading from it is undefined behaviour

    【讨论】:

    • 哦,谢谢,非常感谢。我已经盯着这个项目看了好几个小时了。另外,感谢您解释原因,这真的很有帮助!
    【解决方案2】:

    如果你像这样初始化年份:

    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];
    

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 2013-01-11
      • 2016-10-10
      • 2016-07-06
      • 2018-10-31
      • 2016-08-12
      • 2017-04-29
      • 2021-08-26
      • 1970-01-01
      相关资源
      最近更新 更多