计算数组平均值时出错

Trouble calculating array average

本文关键字:出错 平均值 数组 计算      更新时间:2023-10-16

我对c++还很陌生,有一个问题困扰了我很长时间。我必须编写一个程序,动态分配两个数组,这个数组足够大,可以容纳我创建的游戏中用户定义数量的玩家名称和玩家分数。允许用户在名称-分数对中输入分数。对于每个玩过游戏的玩家,用户键入一个代表学生姓名的字符串,后跟一个代表玩家分数的整数。一旦输入了名称和相应的分数,数组就应该被传递到一个函数中,该函数将数据从最高分数到最低分数进行排序(降序)。应该调用另一个函数来计算平均分数。该程序应显示从得分最高的球员到得分最低的球员的球员名单,以及带有适当标题的平均得分。尽可能使用指针表示法而不是数组表示法

这是我的代码:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void sortPlayers(string[],int[], int);
void calcAvg(int[], int);
int main()
{
    int *scores;
    string *names;
    int numPlayers,
    count;
    cout << "How many players are there?: " << endl;
    cin >> numPlayers;
    scores = new int[numPlayers];
    names = new string[numPlayers];
    for (count = 0; count < numPlayers; count++)
    {
        cout << "Enter the name and score of player " << (count + 1)<< ":" << endl;
        cin >> names[count] >> scores[count];
    }

    sortPlayers(names, scores, numPlayers);
    cout << "Here is what you entered: " << endl;
    for (count = 0; count < numPlayers; count++)
    {
         cout << names[count]<< " " << scores[count] << endl;
    }
    calcAvg(scores, numPlayers);

    delete [] scores, names;
    scores = 0;
    names = 0;
    return 0;

}
void sortPlayers(string names[], int scores[], int numPlayers)
{
    int startScan, maxIndex, maxValue;
    string tempid;
    for (startScan = 0; startScan < (numPlayers - 1); startScan++)
    {
        maxIndex = startScan;
        maxValue = scores[startScan];
        tempid = names[startScan];
        for(int index = startScan + 1; index < numPlayers; index++)
        {
            if (scores[index] > maxValue)
            {
                maxValue = scores[index];
                tempid = names[index];
                maxIndex = index;
                }
            }
            scores[maxIndex] = scores[startScan];
            names[maxIndex] = names[startScan];
            scores[startScan] = maxValue;
            names[startScan] = tempid;
        }
}
void calcAvg(int scores[], int numPlayers)
{ 
    int total = 0;
    double avg = 0;
    for(int i = 0; i < numPlayers; i++)
        total += scores[numPlayers];
    avg = total/numPlayers; 
    cout << "The average of all the scores is: " << fixed << avg << endl;
}

排序部分工作得很好,但我在正确显示平均值方面遇到了问题。每次都显示为负数(例如315788390)有人能帮我解决这个问题吗?这和我的指示有什么关系吗?

在行中

total += scores[numPlayers];

您正在添加一个来自数组外部的值。更改为:

total += scores[i];