[英]C: char logical operator not working
Using the code 使用代码
sscanf(argv[1], "%d", &num1);
sscanf(argv[2], "%c", &op);
sscanf(argv[3], "%d", &num2);
if ((op != '-')||(op != '*')||(op != '/')||(op != '+'))
{
puts("Error:");
printf("'%c' is not a valid operator", op);
return 0;
}
Compiles fine. 编译正常。
However, does not work for any input. 但是,不适用于任何输入。 For instance when the input is 4 + 7
例如,当输入为4 + 7时
Console prints: 控制台打印:
Error:
错误:
'+' is not a valid operator
“ +”不是有效的运算符
Edit: without this error checking code, the rest of the programme operates correctly, including a switch statement based on op! 编辑:没有此错误检查代码,程序的其余部分将正常运行,包括基于op的switch语句!
Makes sense, since your condition is always true. 很有道理,因为您的情况始终是真实的。
(op != '-')||(op != '*')||(op != '/')||(op != '+')
or even 甚至
(op != '-')||(op != '*')
will always evaluate to true
. 将始终评估为
true
。
You're basically saying "If op
is not -
OR op
is not *
... do whatever". 您基本上是说“如果
op
不是-
或者 op
不是*
...则执行任何操作”。
You probably meant to use &&
instead. 您可能打算使用
&&
代替。
You have a logic problem. 你有逻辑上的问题。 You should change the OR (||) operator with AND (&&)
您应使用AND(&&)更改OR(||)运算符
你要
if ((op != '-')&&(op != '*')&&(op != '/')&&(op != '+'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.