gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:58 24 4
gpt4 key购买 nike

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

#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。您的 max 函数也有同样的问题,但可以工作,因为 max 元素不在索引 0 处。

int iMin = 0;

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

关于c++ - 使用函数从数组中索引最小值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43771442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com