2017-05-03 67 views
1

因此我們得到了一個涉及兩個數組的項目(一個字符串,另一個包含值),我決定使用電影和年份。該項目的其中一個參數是顯示最大值和最小值及其字符串。現在,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; 
} 

回答

0

如果最小值是arr[0]然後iMin永遠不會被初始化,因爲if (arr[x] < min)不會返回真正。 您max函數也有同樣的問題,但因爲工作的最大因素不是在索引0

int iMin = 0; 

應該解決您的問題。此外,開發一個習慣總是初始化您的變量和字段是一個好主意。存儲在未初始化變量中的值不確定,reading from it is undefined behaviour

+0

噢謝謝你,我真的很感激。我一直盯着這個項目好幾個小時。此外,謝謝你解釋爲什麼,這真的很有幫助! – Rebeckah

0

如果初始化年是這樣的:

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

,然後最小做工精細,和最大的錯誤^ _^

必須初始化伊明和IMAX,初始號碼需要與ARR指數相同,如下所示:

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