gpt4 book ai didi

c++ - 使用数组作为数组元素时出错

转载 作者:行者123 更新时间:2023-11-30 03:03:40 25 4
gpt4 key购买 nike

我正在类里面学习指针和数组。我的问题出在 dupScore 函数上。我正在尝试找出具有相同分数的学生人数。 scoreArrays 元素编号标识学生并保存分数。

我想创建一个新数组以使用学生分数作为数组的索引。不过,我在 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."
}

最佳答案

scoreArray定义为 double[]所以scoreArray[count]会给你一个double .您需要一个整数才能引用 comparisonArray 中的元素。

for(int count = 0; count < maxStudents; count++)
comparisonArray[(int)scoreArray[count]]++;

这将解决您当前面临的问题,但也会损失很多精度。您可能会考虑更改 double[]int[]如果成绩总是整数。否则,您可能需要查看匹配 scoreArray 元素的不同方法。 .

关于c++ - 使用数组作为数组元素时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9221710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com