当我运行下面的代码时,我发现它会产生一个我不确定如何解决的错误。有人可以帮帮我吗?
#include <iostream>
#include <cstdlib>
using namespace std;
const int n=5;
struct students
{
string firstname;
float rate;
};
students A[n];
students B[n];
void writeStudents(students *TAB){
for(int i=0; i<n; i++){
cout << "First name: ";
cin >> TAB[i].firstname;
cout << "Rate: ";
cin >> TAB[i].rate;
}
}
void printStudents(students *TAB, int rows, float difference){
float average=0;
for(int i=0; i<n; i++){
average = average + TAB[i].rate;
}
average = average/n;
for(int i=n-rows; i<n; i++){
if(TAB[i].rate > average+difference){
cout << TAB[i].firstname << endl;
}
}
}
int main()
{
writeStudents(A[n]);
writeStudents(B[n]);
printStudents(A[n], 2, 0.9);
printStudents(B[n], 3, 1.2);
return 0;
}
error: cannot convert 'students' to 'students*' for argument '1' to 'void writeStudents(students*)' (line 54)
error: cannot convert 'students' to 'students*' for argument '1' to 'void writeStudents(students*)' (line 55)
error: cannot convert 'students' to 'students*' for argument '1' to 'void printStudents(students*)' (line 56)
error: cannot convert 'students' to 'students*' for argument '1' to 'void printStudents(students*)' (line 57)
答案 0 :(得分:3)
在表达式中使用时,A[n]
表示“索引A
处的数组n
的元素”。这有两个原因:首先,您在数组中获得单个元素,并将其传递给期望该数组的函数。第二个问题是索引n
超出范围。
在调用函数时使用普通A
和B
,例如
writeStudents(A);
答案 1 :(得分:0)
这个怎么样(作为第一步)?:
writeStudents(A);
writeStudents(B);
printStudents(A, 2, 0.9);
printStudents(B, 3, 1.2);
答案 2 :(得分:0)
这是你的问题:
writeStudents(A[n]);
writeStudents(B[n]);
printStudents(A[n], 2, 0.9);
printStudents(B[n], 3, 1.2);
请改为尝试:
writeStudents(A);
writeStudents(B);
printStudents(A, 2, 0.9);
printStudents(B, 3, 1.2);