基于Switch语句的成绩评分系统代码运行异常求助
问题排查与修复方案
1. 直接导致无输出的核心问题:scanf格式匹配错误
你的scanf格式字符串写了7个%d,但仅传入了6个变量的地址(&a, &b, &c, &d, &e, &f),这会导致程序持续等待你输入第7个整数——你输入6个成绩后,程序卡在输入阶段,根本没执行到后续输出逻辑。
修复方式:将scanf的格式字符串改为6个%d:
scanf("%d %d %d %d %d %d", &a, &b, &c, &d, &e, &f);
2. 其他潜在问题及修复
void main不符合C标准:C标准规定main函数返回类型应为int,需改为int main(),并在函数末尾添加return 0;。case 5缺少break:当avg等于5时,会先输出Your grade is 5.,随后继续执行default代码输出You are fail.,逻辑矛盾,需给case 5添加break;。- 输出未刷新缓存:所有
printf字符串末尾未加\n,可能导致输出缓存无法及时刷新,建议在每个printf末尾添加换行符,例如:printf("Enter marks of six subjects: \n"); printf("Average is %d\n", avg); - 成绩范围逻辑合理性:若科目成绩为0-100分制,平均分
avg范围是0-100,但当前switch仅处理5-10的情况,逻辑完全不匹配;若为0-10分制,可保留当前case,但需确保输入成绩在合理范围内。
修复后的完整代码
#include <stdio.h> int main() { int a, b, c, d, e, f, avg; printf("Enter marks of six subjects: \n"); scanf("%d %d %d %d %d %d", &a, &b, &c, &d, &e, &f); avg = (a + b + c + d + e + f) / 6; printf("Average is %d\n", avg); switch (avg) { case 10: printf("Your grade is 10.\n"); break; case 9: printf("Your grade is 9.\n"); break; case 8: printf("Your grade is 8.\n"); break; case 7: printf("Your grade is 7.\n"); break; case 6: printf("Your grade is 6.\n"); break; case 5: printf("Your grade is 5.\n"); break; default: printf("You are fail.\n"); } return 0; }
内容的提问来源于stack exchange,提问作者Shivam Narayan
相关产品推荐
相关产品推荐

