switch语句嵌套do-while循环的输入异常问题求助
问题分析与代码修正
问题描述
仅使用switch语句时程序运行正常,但加入do-while循环后,首次执行流程顺畅;第二次及后续循环中,输入1选择继续后,程序会重复执行第一次的运算操作,无法重新选择运算类型,导致运行混乱。
原代码
#include <stdio.h> int main() { int num1, num2, oper, select; printf("Enter the first number:"); scanf("%d", &num1); printf("Enter the second number:"); scanf("%d", &num2); printf("Enter the number 1-5 to for the operations\n"); printf("1-Addition\n"); printf("2-Subtraction\n"); printf("3-Division\n"); printf("4-Multiplication\n"); printf("5-Modulo\n"); scanf("%d", &oper); do{ printf("Press 0 to stop and 1 to continue"); scanf("%d", &select); switch(oper){ case 1: printf("The sum is %d\n", num1+num2); break; case 2: printf("The difference is %d\n", num1-num2); break; case 3: printf("The quotient is %d\n", num1/num2); break; case 4: printf("The product is %d\n", num1*num2); break; case 5: printf("The remainder is %d\n", num1%num2); break;} }while(select == 1); }
错误原因
- 运算类型变量
oper仅初始化一次:scanf("%d", &oper);放在循环外部,只会在程序启动时读取一次运算类型,后续循环不会重新获取用户的新选择,始终使用第一次输入的值。 - 循环执行顺序颠倒:当前逻辑是先询问是否继续,再执行运算,不符合正常交互流程;第一次运算执行依赖外部的
oper输入,后续循环直接重复旧运算,完全偏离预期。
修正后的代码
#include <stdio.h> int main() { int num1, num2, oper, select; do{ // 每次循环重新获取运算数和运算类型 printf("Enter the first number: "); scanf("%d", &num1); printf("Enter the second number: "); scanf("%d", &num2); printf("\nChoose operation (1-5):\n"); printf("1-Addition\n2-Subtraction\n3-Division\n4-Multiplication\n5-Modulo\n"); scanf("%d", &oper); // 执行运算 switch(oper){ case 1: printf("The sum is %d\n", num1+num2); break; case 2: printf("The difference is %d\n", num1-num2); break; case 3: // 新增除数为0的判断,避免运行错误 if(num2 == 0){ printf("Error: Division by zero!\n"); } else { printf("The quotient is %d\n", num1/num2); } break; case 4: printf("The product is %d\n", num1*num2); break; case 5: // 新增模运算除数为0的判断 if(num2 == 0){ printf("Error: Modulo by zero!\n"); } else { printf("The remainder is %d\n", num1%num2); } break; default: printf("Invalid operation choice!\n"); break; } // 询问是否继续 printf("\nPress 0 to stop and 1 to continue: "); scanf("%d", &select); printf("\n"); }while(select == 1); return 0; }
关键修改点
- 将运算数、运算类型的输入逻辑移至
do-while循环内部,确保每次循环都能获取新的输入。 - 调整执行顺序:先输入数据和选择运算,执行运算后再询问是否继续,符合正常交互逻辑。
- 新增除数为0的异常判断,避免程序崩溃。
- 新增
default分支处理无效的运算选择,提升程序健壮性。
内容的提问来源于stack exchange,提问作者Tanish Sharma
相关产品推荐
相关产品推荐

