优化这段代码#include <stdio.h>#define MAX_STUDENTS 100struct student { int id; char name[20]; int score1; int score2; int score3;};int main() { int n; struct student students[MAX_STUDENTS]; printf("请输入学生人数:"); scanf("%d", &n); // 输入学生数据 for (int i = 0; i < n; i++) { printf("请输入第%d个学生的学号、姓名、三门课程成绩:", i+1); scanf("%d%s%d%d%d", &students[i].id, students[i].name, &students[i].score1, &students[i].score2, &students[i].score3); } // 计算三门课程的总平均成绩 double avg1 = 0, avg2 = 0, avg3 = 0; for (int i = 0; i < n; i++) { avg1 += students[i].score1; avg2 += students[i].score2; avg3 += students[i].score3; } avg1 /= n; avg2 /= n; avg3 /= n; printf("三门课程的总平均成绩为:%.2f %.2f %.2f\n", avg1, avg2, avg3); // 找出最高分的学生 int max_index = 0; for (int i = 1; i < n; i++) { if (students[i].score1 + students[i].score2 + students[i].score3 > students[max_index].score1 + students[max_index].score2 + students[max_index].score3) { max_index = i; } } printf("最高分的学生是:%d %s %d %d %d\n", students[max_index].id, students[max_index].name, students[max_index].score1, students[max_index].score2, students[max_index].score3); return 0;}
时间: 2024-01-28 20:05:07 浏览: 139
SeqList.h #include <stdio.h> //包含标准输入输出流的头文件 #include <assert.h
1. 在输入学生数据时,可以使用fgets()函数代替scanf(),以避免缓冲区溢出的问题。改写后的代码如下:
```
for (int i = 0; i < n; i++) {
printf("请输入第%d个学生的学号、姓名、三门课程成绩:", i+1);
scanf("%d", &students[i].id);
fgets(students[i].name, 20, stdin);
scanf("%d%d%d", &students[i].score1, &students[i].score2, &students[i].score3);
}
```
2. 在计算三门课程的总平均成绩时,可以在累加分数的同时计算平均值,避免重复遍历数组。改写后的代码如下:
```
double sum1 = 0, sum2 = 0, sum3 = 0;
for (int i = 0; i < n; i++) {
sum1 += students[i].score1;
sum2 += students[i].score2;
sum3 += students[i].score3;
}
double avg1 = sum1 / n;
double avg2 = sum2 / n;
double avg3 = sum3 / n;
printf("三门课程的总平均成绩为:%.2f %.2f %.2f\n", avg1, avg2, avg3);
```
3. 在找出最高分的学生时,可以使用一个变量记录最高分,避免重复计算总分。改写后的代码如下:
```
int max_index = 0;
int max_score = students[0].score1 + students[0].score2 + students[0].score3;
for (int i = 1; i < n; i++) {
int total_score = students[i].score1 + students[i].score2 + students[i].score3;
if (total_score > max_score) {
max_index = i;
max_score = total_score;
}
}
printf("最高分的学生是:%d %s %d %d %d\n", students[max_index].id, students[max_index].name, students[max_index].score1, students[max_index].score2, students[max_index].score3);
```
综上所述,改进后的代码如下:
阅读全文