#include <stdio.h>
#include <stdlib.h>
struct student{
char initials[2];
int score;
};
void sort(struct student* students, int n){
/*Sort the n students based on their initials*/
int i, j, replace;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(students[j] > students[j+1])
{
replace = students[j];
students[j] = students[j+1];
students[j+1] = replace;
}
}
}
}
int main(){
/*Declare an integer n and assign it a value.*/
int n=10;
/*Allocate memory for n students using malloc.*/
struct student* students = (struct student *)malloc(n*sizeof(struct student));
/*Generate random IDs and scores for the n students, using rand().*/
int i;
for(i=0; i<10; i++){
(students + i)->initials[1] = rand( ) % 26 + 'A';
(students + i)->initials[2] = rand( ) % 26 + 'A';
}
/*Print the contents of the array of n students.*/
for(i=0; i<10; i++){
printf("%c%c\n", students[i].initials[1], students[i].initials[2]);
}
/*Pass this array along with n to the sort() function*/
sort(students, n);
/*Print the contents of the array of n students.*/
return 0;
}
编译此代码时出现以下错误,
Program5.c: In function ‘sort’:
Program5.c:23:23: error: invalid operands to binary > (have ‘struct student’ and ‘struct student’)
if(students[j] > students[j+1])
^
Program5.c:25:17: error: invalid operands to binary == (have ‘int’ and ‘struct student’)
replace == students[j];
^
Program5.c:27:23: error: incompatible types when assigning to type ‘struct student’ from type ‘int’
students[j+1] = replace;
任何帮助将不胜感激:)
最佳答案
前两个错误意味着编译器找不到 >
(大于)运算符或 ==
(等于)运算符来比较 学生
到学生
。编译器不能随便编造一个。您需要编写自己的 >
和 ==
运算符。
第三个错误意味着编译器找不到接受 student
并将其分配给 int
的赋值运算符 (=
) 。同样,您需要编写该运算符,因为编译器不知道您想要发生什么。
您应该能够通过搜索“define c++ == operator”或“define c++赋值运算符”等内容来找到定义这些运算符的正确语法。
关于c - 我的排序程序出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36511629/