因此我們得到了一個涉及兩個數組的項目(一個字符串,另一個包含值),我決定使用電影和年份。該項目的其中一個參數是顯示最大值和最小值及其字符串。現在,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;
}
噢謝謝你,我真的很感激。我一直盯着這個項目好幾個小時。此外,謝謝你解釋爲什麼,這真的很有幫助! – Rebeckah