优化此程序段:void calculate(struct student list,int amount) { int i=0; for(i=0;i<amount;i++) { list[i].score=list[i].s10.3+list[i].s20.3+list[i].s30.4; if(list[i].score>=90) list[i].grade='A'; else if(list[i].score>=80) list[i].grade='B'; else if(list[i].score>=70) list[i].grade='C'; else if(list[i].score>=60) list[i].grade='D'; else list[i].grade='E'; } dispinfo(); view(list,amount); } void findgrade(struct student *list,int amount) { int i=0,j=0; char g; dispinfo(); printf("\n\n\n 请选择您需要查询的等级(输入大写A(优)/B(良)C(中)/D(及格)/E(不及格)): "); g=getchar(); printf("\t\t 学号 总评 等级 \n"); for(i=0;i<amount;i++) { if(list[i].grade==g) { j++; printf("\t\t%10s %6.1f %c \n",list[i].code,list[i].score,list[i].grade); } } printf("\n\n 等级为%c总共有%d人, 总人数%d ,占总人数的%.2lf\n",g,j,amount,(double)j/amount); printf("\n\n\n ****** 按任意键继续! ****** \n"); getch(); }
时间: 2024-04-06 09:32:57 浏览: 21
优化后的程序段如下:
void calculate(struct student list[], int amount) {
for(int i = 0; i < amount; i++) {
float score = list[i].s10.3 + list[i].s20.3 + list[i].s30.4;
list[i].score = score;
if(score >= 90) {
list[i].grade = 'A';
} else if(score >= 80) {
list[i].grade = 'B';
} else if(score >= 70) {
list[i].grade = 'C';
} else if(score >= 60) {
list[i].grade = 'D';
} else {
list[i].grade = 'E';
}
}
dispinfo();
view(list, amount);
}
void findgrade(struct student list[], int amount) {
dispinfo();
printf("\n\n\n 请选择您需要查询的等级(输入大写A(优)/B(良)C(中)/D(及格)/E(不及格)): ");
char g = getchar();
int count = 0;
printf("\t\t 学号 总评 等级 \n");
for(int i = 0; i < amount; i++) {
if(list[i].grade == g) {
count++;
printf("\t\t%10s %6.1f %c \n", list[i].code, list[i].score, list[i].grade);
}
}
printf("\n\n 等级为%c总共有%d人, 总人数%d ,占总人数的%.2lf\n", g, count, amount, (double)count/amount);
printf("\n\n\n ****** 按任意键继续! ****** \n");
getch();
}
主要的优化点如下:
1.在 calculate 函数中,将结构体数组作为参数传入时,应该使用指针类型而不是值类型。这样可以避免数组的拷贝,提高程序的执行效率。
2.在 calculate 函数中,将循环变量 i 的声明和初始化合并到一起。这样可以提高代码的可读性。
3.在 calculate 函数中,将计算总评分数和计算等级的代码分离开来,这样可以使代码更加清晰。
4.在 findgrade 函数中,将查找等级的代码和统计人数的代码分离开来,这样可以使代码更加清晰。
5.在 findgrade 函数中,将循环变量 i 的声明和初始化合并到一起。这样可以提高代码的可读性。
6.在 findgrade 函数中,统计人数时,将计数器 count 的类型改为 int,这样可以提高代码的可读性。