预期的表达式‘/’令牌
我试图编写一个简单的计算程序,其中它只有两个操作数和4个基本操作:“+ - * /”。
我想实现一个函数,如果它检测到不正确的操作,它将退出程序。
如果()函数为if(op!= + - */)
,我将其在中使用。 但是,我不断获得此错误代码:
所讨论的代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char op;
double first, second;
printf("Enter operater sympbol:\n");
scanf("%c", &op);
switch (op)
{
if(op != + - * /)
{
printf("Error. Unidentified operation\n");
exit(0);
}
else
{
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 '/':
printf("%.lf / %.lf = %.lf", first, second, first / second);
}
}
printf("Enter the numbers you wish to compute.(MAX TWO):\n");
scanf("%lf %lf", &first, &second);
return (0);
}
非常感谢任何帮助:)
Im trying to write a simple calculator program where it only has two operands and 4 basic operations: "+ - * /".
I want to implement a function where it exits the program if it detects the incorrect operation.
I have it in an if()
function as if(op != + - * /)
However, I keep getting this error code:
Heres the code in question:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char op;
double first, second;
printf("Enter operater sympbol:\n");
scanf("%c", &op);
switch (op)
{
if(op != + - * /)
{
printf("Error. Unidentified operation\n");
exit(0);
}
else
{
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 '/':
printf("%.lf / %.lf = %.lf", first, second, first / second);
}
}
printf("Enter the numbers you wish to compute.(MAX TWO):\n");
scanf("%lf %lf", &first, &second);
return (0);
}
Any help is greatly appreciated :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这根本不是C的语法工作方式。您要做的要做的必须如下:
错误似乎仅在
/
上失败,但这是因为所有其他运算符都可以用作单一操作员(正数值,否定数值,否定为数字值,指针,指针解雇;但是,您正在尝试比较字符值,而
+
不是字符的字面意义,而是操作员。'+'
是字符字面。请注意,您正在混合不同的语法/语句。您正在结合开关和如果。虽然这可能在句法上正确,但它可能不会给您预期的结果。
由于您使用的是开关/案例,因此不需要检查有效的操作员。只需处理
默认值中的所有未知运算符:
案例:That's simply not how the syntax of C works. What you are trying to do has to be written as follows:
The error seemingly only fails on
/
, but that's because all other operators can be used as unary operators (positive numeric value, negated numeric value, pointer dereference; respectively).But you are trying to compare character values and
+
is not a character literal, but an operator.'+'
is a character literal.Note that you are mixing up different syntaxes/statements. You are combining switch and if. While that might be syntactically correct, it will likely not give you the expected result.
Since you are using switch/case, valid operators do not need to be checked before. Simply handle all unknown operators in the
default:
case: