计算数组平均值时出错
Trouble calculating array average
我对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];
相关文章:
- 计算数组c++的平均值
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 计算平均值,不包括上次得分
- 为x86而非x64编译时出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- 彩色图像的卤化物处理平均值
- 计算数组平均值时出错