C语言switch case中scanf使用问题:输入首个操作数后程序终止
程序输入第一个操作数后崩溃的解决方法
你的原代码:
#include <stdio.h> int main() { char op; int num1, num2; printf("Enter the operation(+,-,/,*,!,^) : "); scanf(" %c", &op); switch (op) { case '+': printf("Enter the first operand : "); scanf(" %d", num1); printf("Enter the second operand : "); scanf(" %d", num2); printf("%d", num1 + num2); break; } }
核心错误
你在case '+'分支的两个scanf调用中,错误地传递了变量num1和num2的值,而非它们的地址。scanf需要通过变量的地址来将输入的值写入变量,直接传值会把变量的初始随机值当作内存地址,写入时访问非法内存,导致程序立刻崩溃。
修正后的代码
#include <stdio.h> int main() { char op; int num1, num2; printf("Enter the operation(+,-,/,*,!,^) : "); scanf(" %c", &op); switch (op) { case '+': printf("Enter the first operand : "); scanf(" %d", &num1); // 添加&取变量地址 printf("Enter the second operand : "); scanf(" %d", &num2); // 添加&取变量地址 printf("%d", num1 + num2); break; } }
补充说明
- 后续实现其他运算符时,务必遵循
scanf读取数值类型变量必须传地址的规则; - 可以额外添加输入合法性检查(比如除法时除数不能为0、阶乘仅接受非负整数等),提升程序健壮性。
内容的提问来源于stack exchange,提问作者Player1 ready
相关产品推荐
相关产品推荐

