2016-12-04 7 views
1

数字を入力しているとき 数字を入力する1 オペレータに入力してくださいERROR:Unknown operator!数字で アキュムレータ= 0.000000 タイプのステップはなぜ単純な「印刷」計算機

- のprintf( "演算子を入力 ")がスキップされ、置き換えられます - デフォルト: の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(char)は、改行文字を消費します。したがって、スキャンされた文字は、あなたが期待しているものではなく、「ラインフィード」です。

私は置き換え:

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

%*c形式を使用して、それを割り当てずにオペレータの前に改行を消費する)

によって

scanf ("%c", &operator); 

をして、あなたのコードがうまく働きました。

+0

Jean-FrançoisFabreありがとうございました!それは今作動する! – Yellowfun

+0

私はそれが賭ける:私はそれをテストした、それらの入力機能はトリッキーです! –

+1

ところで、そのトリックがあれば答えを受け入れることができます。 –

関連する問題