基础计算器程序异常退出求助:未进入运算逻辑即终止
C语言计算器程序未等待运算符输入直接退出的问题解决
我是编程新手,编写了如下C语言基础计算器程序,但程序在输入完两个数字后,未等待我输入运算符就直接退出,无法执行运算逻辑,不清楚问题出在哪里。以下是我的代码和运行输出:
#include <stdio.h> int main() { int a,b,result; char oprtr; printf("Enter the first number\n"); scanf("%d",&a); printf("Enter the second number\n"); scanf("%d",&b); printf("Enter what do you want to do\n"); scanf("%c", &oprtr); if(oprtr=='+') { result=a+b; printf("Addition = %d + %d = %d\n",a,b,result); } else if(oprtr=='-') { result=a-b; printf("Subtraction = %d - %d = %d\n",a,b,result); } else if(oprtr=='*') { result=a*b; printf("Multiplication = %d - %d = %d\n",a,b,result); } else if(oprtr=='/') { result=a/b; printf("Division = %d / %d = %d",a,b,result); } return 0; }
运行输出:
Enter the first number 5 Enter the second number 2 Enter what do you want to do ...Program finished with exit code 0 Press ENTER to exit console.
问题原因
scanf("%d", &b);读取完第二个数字后,你按下的**回车键(换行符\n)**会残留在输入缓冲区中。后续的scanf("%c", &oprtr);会直接读取这个换行符,而非等待你输入运算符,导致程序进入判断逻辑后,换行符不匹配任何运算符分支,最终无运算输出直接退出。
解决方法
处理输入缓冲区残留的换行符,两种常用方案:
- 在读取运算符的
%c格式符前添加空格:scanf(" %c", &oprtr);,空格会自动跳过所有空白字符(包括换行、空格、制表符) - 在读取运算符前调用
getchar();,手动吃掉缓冲区中的换行符
修正后的代码
#include <stdio.h> int main() { int a, b, result; char oprtr; printf("Enter the first number\n"); scanf("%d", &a); printf("Enter the second number\n"); scanf("%d", &b); printf("Enter what do you want to do\n"); // 通过空格跳过缓冲区中的空白字符 scanf(" %c", &oprtr); if(oprtr == '+') { result = a + b; printf("Addition = %d + %d = %d\n", a, b, result); } else if(oprtr == '-') { result = a - b; printf("Subtraction = %d - %d = %d\n", a, b, result); } else if(oprtr == '*') { result = a * b; // 修正原代码中乘法输出的格式错误(将-改为*) printf("Multiplication = %d * %d = %d\n", a, b, result); } else if(oprtr == '/') { // 增加除数为0的判断,避免程序崩溃 if(b == 0) { printf("Error: Division by zero is not allowed.\n"); } else { result = a / b; printf("Division = %d / %d = %d\n", a, b, result); } } else { // 新增非法运算符提示,提升程序健壮性 printf("Invalid operator entered.\n"); } return 0; }
额外优化说明
- 修复了原代码中乘法输出语句的格式错误(误将
*写为-) - 添加除数为0的判断逻辑,防止程序因非法运算崩溃
- 增加非法运算符的提示分支,让程序对异常输入更友好
内容的提问来源于stack exchange,提问作者Nayif Noushad
相关产品推荐
相关产品推荐

