2016-07-07 68 views
0

我從我的教科書中複製了一個簡單的「計算器」示例,它接受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

回答

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

謝謝,有沒有在較短代碼中實現相同結果的方法? – AGN

+0

@AGN你可能會考慮'while(strchr(「+ - * /」,operator)&& operator);'short。 – chux