2016-12-04 77 views
1

當我在一個數字我打字我看到 輸入一個數字1 鍵入操作錯誤:未知的操作! 累加器= 0.000000 鍵入一個數字一個簡單的「印刷」計算器

爲什麼步驟 - 輸出( 「在操作員鍵入 」)被跳過,被替換爲 - 默認: 的printf(「 ERROR:未知操作者\ N!」); 休息;

感謝您的幫助!

// Program to produce a simple printing calculator 

#include <stdio.h> 
#include <stdbool.h> 

int main (void) 
{ 

    double accumulator = 0.0, number; // The accumulator shall be 0 at startup 
    char operator; 
    bool isCalculating = true; // Set flag indicating that calculations are ongoing 


    printf("You can use 4 operator for arithmetic + -/*\n"); 
    printf("To set accumulator to some number use operator S or s\n"); 
    printf("To exit from this program use operator E or e\n"); 
    printf ("Begin Calculations\n"); 

    while (isCalculating) // The loop ends when operator is = 'E' 
    { 

     printf("Type in a digit "); 
     scanf ("%lf", &number);    // Get input from the user. 

     printf("Type in an operator "); 
     scanf ("%c", &operator); 
     // The conditions and their associated calculations 
     switch (operator) 
     { 
     case '+': 
      accumulator += number; 
      break; 
     case '-': 
      accumulator -= number; 
      break; 
     case '*': 
      accumulator *= number; 
      break; 
     case '/': 
      if (number == 0) 
       printf ("ERROR: Division by 0 is not allowed!"); 
      else 
       accumulator /= number; 
      break; 
     case 'S': 
     case 's': 
      accumulator = number; 
      break; 
     case 'E': 
     case 'e': 
      isCalculating = false; 
      break; 
     default: 
      printf ("ERROR: Unknown operator!\n"); 
      break; 
     } 

     printf ("accumulator = %f\n", accumulator); 
    } 
    printf ("End of Calculations"); 

    return 0; 
} 

回答

2

scanf對於字符消耗換行符。所以被掃描的字符是「換行」而不是你期望的字符。

我代替:

scanf ("%c", &operator); 

通過

scanf ("%*c%c", &operator); 

(消耗運算符之前換行,而無需使用%*c格式分配給它)

和你的代碼工作的罰款。

+0

謝謝你讓·弗朗索瓦·法布爾!它現在工作! – Yellowfun

+0

我敢打賭:我測試過了,那些輸入函數很棘手! –

+1

順便說一句,你可以接受答案,如果它伎倆。 –