2017-02-20 13 views
-1

私は単純な温度変換器を作ろうとしています。すべて私にはうまく見えますが、なぜスキャン入力が認識されないのか分かりません。 お時間をいただきありがとうございます。あなたは、その空白はその後、TEMために挿入される温度を挿入終了する空白文字を入力したときにC if文がスキャン入力を認識しない

#include <stdio.h> 
    exercise1(){ 
     float a; 
     char tem; 
     printf("--- Temperature Converter ---\n"); 
     printf("Please enter a temperature: "); 
     scanf("%f", &a); 
     printf("\nWould you like to convert to Celsius or Fahrenheit? (c or f)"); 
     scanf("%c", &tem); getchar(); 
     if (tem == 'c'){ 
      a = ((float)a-32) * 5.0f/9.0f; 
      printf("\nYour temperature is %g\n", &a); 
     } 
     else if (tem == 'f'){ 
      a = (float)a * 9.0f/5.0f + 32; 
      printf("\nYour temperature is %g\n", &a); 
     } 
     else 
      printf("\nPlease enter a valid conversion type!\n"); 
     } 
    } 
+2

(機能を閉じるには、一つだけが必要とされている)%グラム 3.あなたが他の最後の後に}あまり使用されていない、山車をスキャンする 2.%のFを(コンパイル中に警告を注意してください) \ n "、\\"、a); ' – BLUEPIXY

+0

おそらくあなたが' getchar'を呼び出しているので、 'printf(" \ n "温度は%g \ n"、&a); 'remove'& ' - >' printfちなみに、 'float a'ではコードの後ろに'(float)a'の必要はありませんが(それは完全に意味論的です) – goodvibration

+0

ありがとうございました。 。 – Abdo

答えて

1

のscanf()で問題となりました。 これを防ぐには、以下のようにscanf()の前にgetchar()を使用します。

注:あなたの回答を確認すると、 "%c"の代わりに "%c"を使用することをお勧めします。これは良い考えであり、うまくいきます。 1. printf()を使用するときは、&を送信しないでください。代わりに。 printf()はポインタを必要とせず、変数を必要とします。

#include <stdio.h> 
void main(){ 
     float a; 
     char tem; 
     printf("--- Temperature Converter ---\n"); 
     printf("Please enter a temperature: "); 
     scanf("%f", &a); 
     printf("\nWould you like to convert to Celsius or Fahrenheit? (c or f)"); 
     getchar(); 
     scanf("%c", &tem); 
     if (tem == 'c'){ 
       a = ((float)a-32) * 5.0f/9.0f; 
       printf("\nYour temperature is %f\n", a); 
     } 
     else if (tem == 'f'){ 
       a = (float)a * 9.0f/5.0f + 32; 
       printf("\nYour temperature is %f\n", a); 
     } 
     else 
       printf("\nPlease enter a valid conversion type!\n");} 
関連する問題