我正在学习类中的指针和数组。我的麻烦在于dupScore功能。 我想找到得分相同的学生人数。 scoreArrays元素编号标识学生并保留分数。
我想创建一个新数组,将学生得分用作数组的索引。不过我在得分阵容下得到了一个红色的波浪形。错误是“表达式必须是整数或枚举”
for(int count = 0; count < maxStudents; count++)
comparisonArray[scoreArray[count]]++;
这是我的整个代码。
#include <iostream>
using namespace std;
const int maxStudents = 30;
void readScores(double[]);
void gradeCounter(double[],int&,int&,int&,int&,int&);
int dupScore(double[]);
void readoutFunc(double[], int, int, int, int, int, int);
int main()
{
int As = 0, Bs = 0, Cs = 0, Ds = 0, Fs = 0; // Distribution of scores
int sameScore = 0;
double scoreArray[maxStudents];
readScores(scoreArray);//Read in Scores
gradeCounter(scoreArray, As, Bs, Cs, Ds, Fs);//Count letter grades
sameScore = dupScore(scoreArray);//Detect duplicate scores
system ("PAUSE");
return 0;
}
void readScores(double scoreArray[])
{
double *scorePTR;
scorePTR = scoreArray;
for(int count = 0; count < maxStudents; count++)
{
cout<<"Please enter score for student "<<count+1<<" or -999 to end.\n";
cin>>*(scorePTR+count);
if(*(scorePTR+count) == -999)
break;
}
}
void gradeCounter(double scoreArray[],int &As,int &Bs,int &Cs,int &Ds,int &Fs)
{
double *scorePTR2;
scorePTR2 = scoreArray;
for(int count = 0; count < maxStudents; count++)
{
if(scoreArray[count] >= 90)
As+=1;
else if(*(scorePTR2+count) >= 80 && *(scorePTR2+count) < 90)
Bs+=1;
else if(*(scorePTR2+count) >= 70 && *(scorePTR2+count) < 80)
Cs+=1;
else if(*(scorePTR2+count) >= 60 && *(scorePTR2+count) < 70)
Ds+=1;
else if(*(scorePTR2+count) >= 0 && *(scorePTR2+count) < 60)
Fs+=1;
}
}
int dupScore(double scoreArray[])
{
const int maxGrade = 101;
double comparisonArray[maxGrade];
int sameScores = 0;
for(int count = 0; count < maxStudents; count++)
comparisonArray[scoreArray[count]]++;
for(int count2 = 0; count2 < maxGrade; count2++)
{
if(comparisonArray[count2] > 0)
sameScores+=1;
}
return sameScores;
}
void readoutFunc(double scoreArray[], int As, int Bs, int Cs, int Ds, int Fs, int sameScore)
{
int numofStudents = 0;
for(int count = 0; scoreArray[count] >= 0; count++)
{
numofStudents += 1;
}
cout<<"\n\nReport";
cout<<"\n---------";
cout<<"\nNumber of students: "<<numofStudents;
cout<<"\nNumber of As: "<<As;
cout<<"\nNumber of Bs: "<<Bs;
cout<<"\nNumber of Cs: "<<Cs;
cout<<"\nNumber of Ds: "<<Ds;
cout<<"\nNumber of Fs: "<<Fs;
cout<<"\n\n"<<sameScore<<" students have the same score."
}
答案 0 :(得分:2)
scoreArray
定义为double[]
,因此scoreArray[count]
会为您提供double
。您需要一个整数才能引用comparisonArray中的元素。
for(int count = 0; count < maxStudents; count++)
comparisonArray[(int)scoreArray[count]]++;
这将解决您目前面临的问题,但也会失去很多精确度。如果成绩始终为整数,您可以考虑将double[]
更改为int[]
。否则,您可能需要查看匹配scoreArray
的元素的其他方法。
答案 1 :(得分:1)
scoreArray
是double
的数组,您不能使用double
索引数组(当您执行comparisonArray[scoreArray[count]]
时,您尝试执行此操作。