2017-01-22 21 views
-1

私はCプログラミングの初心者で、自分のコードでif-else文を使って電卓を作ったところです。そして、switch-statementを使って同じことをしようとしましたが、常にデフォルトを実行しています。私のコードを見て、間違っていることを教えてください。 現在、CodeBlockでコードを書いています。switch文を使用してCで簡単な電卓を作成する

This is the message i'm getting

int main() 
{ 
    printf("\nWhat operation do you want to do:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n"); 
    float num1; 
    printf("Please enter the first number: "); 
    scanf("%f", &num1); 
    float num2; 
    printf("Please enter the second number: "); 
    scanf("%f", &num2); 
    char myChar; 
    scanf("%c", &myChar); 
    switch (myChar) 
    { 
     case 'A': 
      printf("The addition of %.2f and %.2f is %.2f", num1, num2, num1 + num2); 
      break; 
     case 'B': 
      printf("The subtraction of %.2f and %.2f is %.2f", num1, num2, num1 - num2); 
      break; 
     case 'C': 
      printf("The multiplication of %.2f and %.2f is %.2f", num1, num2, num1 * num2); 
      break; 
     case 'D': 
      printf("The quotient of %.2f and %.2f is %.2f", num1, num2, num1/num2); 
      break; 
     default : 
      printf("You enterned incorrect input"); 
      break; 
    } 
    return 0; 
} 

任意の助け

+0

'char myChar; – BLUEPIXY

+0

'scanf("%c "、&myChar)'を実行すると、2番目の数値を読み込んだ後に改行を読み込んでいます。あなたの 'switch()'は大文字小文字を持っていないので、デフォルトを実行します。 – Dmitri

+0

行を読み取る場合は、行または行を読み取るコードを使用し、文字または数値を読み取るコードでは使用しないでください。表示されているようにコードを動作させるには、コードが2つの数字と1文字を読み込むので、 "32 43+ "と入力する必要があります。 –

答えて

0

あなたの問題は、以前の入力から残り\nは、1つの入力として解釈されたことscanfにほとんど関連して理解されるであろう。

また、操作のプロンプトと対応する入力が一致しません。

は修正を提案する:

float num1; 
printf("Please enter the first number: "); 
scanf("%f", &num1); 

float num2; 
printf("Please enter the second number: "); 
scanf("%f", &num2); 

printf("\nWhat operation do you want to do:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n"); 
char myChar; 
scanf(" %c", &myChar); 

あなたが目的をデバッグするようprintfを追加することができます - あまりにも、役立つだろうという。最初の入力の例:

float num1; 
printf("Please enter the first number: "); 
scanf(" %f", &num1); 
printf("num1 = %f\n", num1); 
+1

'" "'%f "'の前に重複している可能性があります。 – melpomene

+0

@melpomene私の悪い "%f"はスペースをスキップします.. – artm

関連する問題