比方說,我寫這一段代碼:不期望的雙重複
char c; // c from choise.
do{
printf("Please choose one of the following operators:\n");
printf("+ for Addition\n- for Subtraction\n* for Multiplication\n/ for Division\n");
printf("= for Assignment and\nE to check if two variables have the same type and value.\n");
scanf("%c", &c);
}while(c!='+' && c!='-' && c!='*' && c!='/' && c!='=' && c!='E');
的主要問題是,用戶將數字或字母時,一切除了上述運營商內部的每個消息printf在屏幕上出現兩次。
例如,如果c = 'A',我們有:
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/for Division
= for Assignment and
E to check if two variables have the same type and value.
A //wrong answer, the loop continues...
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/for Division
= for Assignment and
E to check if two variables have the same type and value.
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/for Division
= for Assignment and
E to check if two variables have the same type and value.
//here the program awaits the new value of c.
但是,如果c = ' - ' 或c = '+' 等,當然我們有
Please choose one of the following operators:
+ for Addition
- for Subtraction
* for Multiplication
/for Division
= for Assignment and
E to check if two variables have the same type and value.
- // or +
//the program goes to the next line.
當我嘗試在while或for循環中轉換do_while循環時,發生了同樣的事情。
如果您不想讓它們重複,請將打印件移出循環! – pmg
試試這個'scanf(「%c」,&c);' – haccks
@haccks它很有效!非常感謝!你能解釋爲什麼嗎?這個圓括號裏面的空間對我來說是個謎! – George