我对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;
}
排序部分工作正常,但我有平均正常显示的麻烦。它每次显示为负数(例如-3157838390) 任何人都可以帮我解决这个问题吗?它与我的指针有什么关系?
的“这里是你输入的内容”行只是进行检查,看该阵列正常工作... – 2014-08-31 02:55:39
我不能过分强调学习得到[最小的完整的例子]的重要性(http://stackoverflow.com/help/mcve)。 – Beta 2014-08-31 02:59:54
如果您使用调试器,我会在calcAvg函数中放置一个断点,并查看数组的外观和总共在做什么等。 – justanotherdev 2014-08-31 03:01:53