使用函数从数组中索引最小值的问题
Problems with Indexing Minimum value from array using a function
因此,我们得到了一个涉及两个阵列(一个字符串,另一个包括值(的项目,我决定使用电影和数年。该项目的参数之一是显示最大值和最小值及其字符串。现在,最大功能正常,但是当我尝试运行最小值时,它说不是初始化的。我在做什么错?
#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];
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用递归的数组的最小值.这是怎么回事
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- txt 文件中浮点数的最大和最小值
- 余数运算符的等效操作,用于处理低于允许的最小值
- 需要使用模板查找数组的第二个最小和最小值
- CUDA - 将 float3 数组的 (x,y,z) 分量的最小值/最大值分开?
- 查找包含 N 个元素的数组的最小值和最大值
- 在不进行排序的情况下查找数组中n个最小值的索引
- 在索引0为0的数组中查找非零最小值C++
- 包含全局最小值的向量索引
- 使用函数从数组中索引最小值的问题
- C++:仅在具有指定索引的元素中查找数组中的最小值
- 在 for 循环中查找最小值并保留其索引
- 矢量中最大值和最小值的索引