2015-02-17 56 views
1

作爲c編程的新手(我只有視覺基本經驗),我不完全確定如何在條件語句中更改字符串變量的while循環應該如何工作。雖然循環更改字符串變量

下面的代碼是一個簡單的計算器,我可以讓用戶輸入一個操作和兩個數字,然後輸出相應的結果。我試圖在一個while循環中進行編碼,這個循環不斷重複這個過程,直到用戶決定退出它。但似乎行scanf(「%c」,&退出);不會影響while循環條件語句。

#include <stdio.h> 

int main() { 
float num1, num2; 
char operation; 
char quit = "n"; 
while (quit = "n"){ 
printf("Enter an operator (+, -, *, /) \n"); 
scanf(" %c", &operation); 
printf("Enter the numbers you wish to carry out the operation on \n"); 
scanf("%f %f", &num1, &num2); 
    switch(operation) { 
     case '+': 
      printf("%f\n", num1+num2); 
      break; 
     case '-': 
      printf("%f\n", num1-num2); 
      break; 
     case '*': 
      printf("%f\n", num1*num2); 
      break; 
     case '/': 
      printf("%f\n", num1/num2); 
      break; 

    } 
printf("Would you like quit the program, is so enter 'y' \n"); 
scanf("%c", &quit); 
} 
return 0; 
} 

感謝您提前給予的所有幫助。

+0

'焦炭退出= 「N」;'是不是C. – 2015-02-17 21:31:42

+0

對單引號之間的區別讀了雙引號 – 2015-02-17 21:40:38

+0

啓用所有編譯器警告,並注意它們。 – twalberg 2015-02-17 21:56:40

回答

-2

那是因爲你是在爲你而循環分配的,而不是檢查其價值的退出變量的值,更換while (quit = "n")

使用==爲=

while(quit == "n"){...} 
+0

雖然運算符的選擇當然是錯誤的,但它也是不正確的,無法將單個字符與靜態字符串進行比較這樣的字面意思,並希望得到任何有意義的... – twalberg 2015-02-17 21:57:39

+0

感謝您的幫助,這樣一個簡單的錯誤,從來沒有知道有檢查值的不同操作, - 在視覺基本,似乎一個等號做這兩個功能 - – Tarius 2015-02-17 22:04:54

+0

這個答案確實解決了我遇到的問題,我認爲反對票只是因爲雙引號用於單個字符而不是單引號。 – Tarius 2015-02-17 23:02:32

0

你可以做這樣的

#include <stdio.h> 
int main() { 
float num1, num2; 
char operation; 
char quit = 'n'; 
//while (quit = "n") // 
    while (quit!= 'y') 
{ 
printf("Enter an operator (+, -, *, /) \n"); 
scanf(" %c", &operation); 
printf("Enter the numbers you wish to carry out the operation on \n"); 
scanf("%f %f", &num1, &num2); 
switch(operation) { 
    case '+': 
     printf("%f\n", num1+num2); 
     break; 
    case '-': 
     printf("%f\n", num1-num2); 
     break; 
    case '*': 
     printf("%f\n", num1*num2); 
     break; 
    case '/': 
     printf("%f\n", num1/num2); 
     break; 

} 
printf("Would you like quit the program, is so enter 'y' \n"); 
scanf("%c", &quit); 
} 
return 0; 
}