我從我的教科書中複製了一個簡單的「計算器」示例,它接受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;
}
問題尋求調試幫助(「爲什麼不是這個代碼工作?「)必須包含所需的行爲,特定的問題或錯誤以及在問題本身中重現問題所需的最短代碼。沒有明確問題陳述的問題對其他讀者無益。請參閱:如何創建最小,完整和可驗證示例。 1 – Olaf
您需要'&&'而不是'||'。否則,你的邏輯表達式總會成功。它應該等於'!(operator =='+'|| operator ==' - '|| operator =='*'|| operator =='/')' – lurker
讀取循環體並調出大聲,說'||'爲「或」。 – Olaf