2017-05-03 1 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

최소값은 if (arr[x] < min)사실을 반환하지 않습니다 때문에 arr[0] 다음 iMin 이제까지 초기화되지 않습니다 경우. 당신 최대 기능은 동일한 문제를 가지고 있지만 최대 요소는 인덱스 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}; 

하고, 최소 잘 작동하고 최대 오류입니다^_^

당신이 IMIN과 아이 맥스 (IMAX) 영화관, 초기을 초기화해야

번호는 다음과 같이 arr 색인과 동일해야합니다.