做...逻辑运算符while循环

问题描述:

我从我的教科书中复制了一个简单的“计算器”示例,它接受2个值和一个运算符。但是,它不检查输入的表达式是否有效。代码应该提示用户,直到输入正确的表达式。做...逻辑运算符while循环

我该如何解决这个问题?什么是更好的方式来做到这一点?

/* 
Input: A simple expression with 2 values and 1 operator 
Format: value1 (operator) value2 
Ex: 5*5 
Output: Answer 
*/ 

#include <stdio.h> 

int main (void) 
{ 
float value1, value2; 
char operator = ' '; 

//Issue Area, the while section does not work 
do 
{ 
    printf ("Type in your expression:"); 
    scanf ("%f %c %f", &value1, &operator, &value2); 
} 
while ((operator != '+' || operator != '-' || operator != '*' || operator != '/')); 

//This is fine, code is for an else...if example in textbook 
if (operator == '+') 
    printf ("%.2f\n",value1 + value2); 
else if (operator == '-') 
    printf ("%.2f\n",value1 - value2); 
else if (operator == '*') 
    printf ("%.2f\n",value1 * value2); 
else if (operator == '/') 
    printf ("%.2f\n",value1/value2); 

return 0; 
} 
+0

问题寻求调试帮助(“为什么不是这个代码工作?“)必须包含所需的行为,特定的问题或错误以及在问题本身中重现问题所需的最短代码。没有明确问题陈述的问题对其他读者无益。请参阅:如何创建最小,完整和可验证示例。 1 – Olaf

+6

您需要'&&'而不是'||'。否则,你的逻辑表达式总会成功。它应该等于'!(operator =='+'|| operator ==' - '|| operator =='*'|| operator =='/')' – lurker

+0

读取循环体并调出大声,说'||'为“或”。 – Olaf

您有:

do 
{ 
    ... 
} 
while ((operator != '+' || operator != '-' || operator != '*' || operator != '/')); 

在有条件的while的使用||是错误的。

比方说operator的值是'+'。然后,while计算结果为:

while ((false || true || true || true)); 

计算结果为

while (true); 

无论什么operator值,其中至少有三个子表达式将评估对true。因此,条件将始终评估为true。您需要使用&&而不是||

do 
{ 
    ... 
} 
while ((operator != '+' && operator != '-' && operator != '*' && operator != '/')); 

一种可能的方式,使代码更清晰是:

do 
{ 
    ... 
} 
while (!isValidOperator(operator)); 

其中

int isValidOperator(char operator) 
{ 
    return (operator == '+' || 
      operator == '-' || 
      operator == '*' || 
      operator == '/'); 
} 

可以使代码在isValidOperator较短的使用:

int isValidOperator(char operator) 
{ 
    return (operator != '\0' && strchr("+-*/", operator) != NULL); 
} 
+0

谢谢,有没有在较短代码中实现相同结果的方法? – AGN

+0

@AGN你可能会考虑'while(strchr(“+ - * /”,operator)&& operator);'short。 – chux