2017-04-03 51 views
0

我正在嘗試創建一個程序,用戶可以輸入多達100個玩家的名字和分數,然後打印出所有玩家的名字和分數,然後輸入平均得分,最後,顯示球員的得分低於平均水平。除了最後一部分,我已經設法做到了所有這些,顯示低於平均分數。我不確定如何去做。在我的DesplayBelowAverage函數中,我試圖讓它讀取當前玩家的分數並將其與平均值進行比較,以查看是否應將其打印爲低於平均值的分數,但它似乎無法識別我創建的averageScore值在CalculateAverageScores函數中。這裏是我的代碼:在玩家得分程序中顯示低於平均分數

#include <iostream> 
#include <string> 

using namespace std; 

int InputData(string [], int [], int); 
int CalculateAverageScores(int [], int); 
void DisplayPlayerData(string [], int [], int); 
void DisplayBelowAverage(string [], int [], int); 


void main() 
{ 
    string playerNames[100]; 
    int scores[100]; 


    int sizeOfArray = sizeof(scores); 
    int sizeOfEachElement = sizeof(scores[0]); 
    int numberOfElements = sizeOfArray/sizeOfEachElement; 

    cout << numberOfElements << endl; 

    int numberEntered = InputData(playerNames, scores, numberOfElements); 

    DisplayPlayerData(playerNames, scores, numberEntered); 

    CalculateAverageScores(scores, numberEntered); 


    cin.ignore(); 
    cin.get(); 
} 

int InputData(string playerNames[], int scores[], int size) 
{ 
    int index; 

    for (index = 0; index < size; index++) 
    { 
     cout << "Enter Player Name (Q to quit): "; 
     getline(cin, playerNames[index]); 
     if (playerNames[index] == "Q") 
     { 
      break; 
     } 

     cout << "Enter score for " << playerNames[index] << ": "; 
     cin >> scores[index]; 
     cin.ignore(); 
    } 

    return index; 
} 


void DisplayPlayerData(string playerNames[], int scores[], int size) 
{ 
    int index; 

    cout << "Name  Score" << endl; 

    for (index = 0; index < size; index++) 
    {  
     cout << playerNames[index] << "  " << scores[index] << endl;  
    } 
} 

int CalculateAverageScores(int scores[], int size) 
{ 
    int index; 
    int totalScore = 0; 
    int averageScore = 0; 

    for (index = 0; index < size; index++) 
    {  
     totalScore = (totalScore + scores[index]);    
    } 
    averageScore = totalScore/size; 
    cout << "Average Score: " << averageScore; 

    return index; 
} 

void DisplayBelowAverage(string playerNames[], int scores[], int size) 
{ 
    int index; 

    cout << "Players who scored below average" << endl; 
    cout << "Name  Score" << endl; 

    for (index = 0; index < size; index++) 
    {  
     if(scores[index] < averageScore) 
     { 
      cout << playerNames[index] << "  " << scores[index] << endl; 
     } 
    } 
} 

回答

1

您計算在CalculateAverageScoreaverageScore變量,它是局部的功能只有這麼DisplayBelowAverage沒有關於averageScore價值理念。這就是爲什麼你的邏輯不起作用。

爲了解決這有兩種選擇:

  1. 聲明averageScore全球(儘管它不是最好有全局變量)

  2. 傳遞averageScoreDisplayBelowAverage作爲參數。這是一個更好的方法。因此,您應該做的是返回您在CalculateAverageScore中計算的平均分並將其存儲在某個變量中,然後將其作爲參數傳遞給DisplayBelowAverage函數。

希望這有助於

+0

是的,這個工作。感謝您的幫助。 – jackofblaze

+0

樂於幫助,我希望你使用第二種方法 – Ezio