2017-04-03 47 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