C语言编写四则运算计算器报'/'前缺表达式编译错误求助
问题根因
编译报错Expected expression before ‘/’ token和代码逻辑异常来自三处错误:
- 条件判断语法错误:C语言不支持
if(op != + - * /)这种写法。+ - * /作为待匹配的字符值,必须用单引号包裹,且多值不等判断需要用逻辑与&&连接每个独立判断条件,直接堆叠符号会被编译器识别为算术运算表达式,触发语法错误。 - 结构嵌套错误:
if/else语句不能直接放在switch的case块外层,switch结构内部仅允许放置case标签、default标签和对应分支的执行语句。 - 执行顺序错误:读取运算数的
scanf被放在了运算逻辑之后,执行计算时first和second变量未被赋值,会输出随机垃圾值。
修正后可运行代码
使用switch自带的default分支处理非法运算符是更简洁的实现方式,同时调整了代码执行顺序,补全了除法除零的边界判断:
#include <stdio.h> #include <stdlib.h> int main(void) { char op; double first, second; printf("Enter operator symbol:\n"); scanf("%c", &op); printf("Enter the numbers you wish to compute.(MAX TWO):\n"); scanf("%lf %lf", &first, &second); switch (op) { case '+': printf("%.lf + %.lf = %.lf", first, second, first + second); break; case '-': printf("%.lf - %.lf = %.lf", first, second, first - second); break; case '*': printf("%.lf * %.lf = %.lf", first, second, first * second); break; case '/': if (second == 0) { printf("Error. Divisor cannot be 0\n"); exit(1); } printf("%.lf / %.lf = %.lf", first, second, first / second); break; default: printf("Error. Unidentified operation\n"); exit(0); } return 0; }
如果坚持用if语句做非法运算符校验,正确写法如下,校验逻辑需要放在switch结构外部:
if(op != '+' && op != '-' && op != '*' && op != '/') { printf("Error. Unidentified operation\n"); exit(0); }
内容的提问来源于stack exchange,提问作者chris122
相关产品推荐
相关产品推荐

