我对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;
}
排序部分工作正常,但我在正常显示时遇到问题。每次都显示为负数(ex -3157838390) 任何人都可以帮我解决这个问题吗?它与我的指针有什么关系吗?
答案 0 :(得分:2)
在这一行
total += scores[numPlayers];
您正在从数组外部添加值。将其更改为:
total += scores[i];