这个代码在写入性别时程序错误,请修改成能正确运行的#include <stdio.h> struct student { int num; char name[10]; char gender; int c, oop, db; float avg; }; int main() { int i, j; struct student s[5], temp; for (i = 0; i < 5; i++) { printf("请输入第%d个学生的信息,学号,姓名,性别,C语言,oop ,数据库:\n", i + 1); scanf("%d%s %c%d%d%d", &s[i].num, s[i].name, &s[i].gender, &s[i].c, &s[i].oop, &s[i].db); s[i].avg = (float)(s[i].c + s[i].oop + s[i].db) / 3.0; } for (i = 0; i < 4; i++) { for (j = 0; j < 4 - i; j++) { if (s[j].avg < s[j+1].avg) { temp = s[j]; s[j] = s[j+1]; s[j+1] = temp; } } } printf("\n学号 姓名 性别 c语言 oop 数据库 平均成绩\n"); for (i = 0; i < 5; i++) { printf("%-10d%-10s%-8c%-8d%-8d%-8d%-6.1f\n", s[i].num, s[i].name, s[i].gender, s[i].c, s[i].oop, s[i].db, s[i].avg); } return 0; }
时间: 2024-04-26 17:24:25 浏览: 93
在 scanf 函数中,读取字符类型时应该使用 %c,而不是 %s。因此,将代码中的第 16 行修改为:
scanf("%d%s %c%d%d%d", &s[i].num, s[i].name, &s[i].gender, &s[i].c, &s[i].oop, &s[i].db);
修改后的完整代码如下:
#include <stdio.h>
struct student {
int num;
char name[10];
char gender;
int c, oop, db;
float avg;
};
int main() {
int i, j;
struct student s[5], temp;
for (i = 0; i < 5; i++) {
printf("请输入第%d个学生的信息,学号,姓名,性别,C语言,oop ,数据库:\n", i + 1);
scanf("%d%s %c%d%d%d", &s[i].num, s[i].name, &s[i].gender, &s[i].c, &s[i].oop, &s[i].db);
s[i].avg = (float)(s[i].c + s[i].oop + s[i].db) / 3.0;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 4 - i; j++) {
if (s[j].avg < s[j+1].avg) {
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
printf("\n学号 姓名 性别 c语言 oop 数据库 平均成绩\n");
for (i = 0; i < 5; i++) {
printf("%-10d%-10s%-8c%-8d%-8d%-8d%-6.1f\n", s[i].num, s[i].name, s[i].gender, s[i].c, s[i].oop, s[i].db, s[i].avg);
}
return 0;
}
阅读全文