Do ... while循环使用逻辑运算符

时间:2016-07-07 19:47:58

标签: c

我复制了一个简单的"计算器"我的教科书中的例子,它接受2个值和一个运算符。但是,它不会检查输入的表达式是否有效。代码应提示用户,直到输入正确的表达式。

我应该如何解决我的风格?有什么更好的方法呢?

/*
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;
}

1 个答案:

答案 0 :(得分:3)

你有:

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);
}