2017-05-24 2 views
1

メニューから選択する必要がある次のコードを記述しました。プログラムのメニューが2回表示されました

#include <stdio.h> 
char start(void); 
char first(void); 
float firstn(void); 
int main(void) 
{ 
    int choice; 
    while((choice=start())!='q') 
    { 
     switch(choice) 
     { 
      case'a': 
       firstn(); 
       printf("yeah\n"); 
       break; 
      case's': 
       firstn(); 
       printf("yeah\n"); 
       break; 
      case'm': 
       firstn(); 
       printf("yeah\n"); 
       break; 
      case'd': 
       firstn(); 
       printf("yeah\n"); 
       break; 
     } 
    } 
    printf("Bye."); 
    return 0; 
} 
char start(void) 
{ 
    int ch; 
    printf("Enter the operation of your choice:\n"); 
    printf("a. add   s. subtract\n"); 
    printf("m. multiply  d. divide\n"); 
    printf("q. quit\n"); 
    ch=first(); 
    while(ch!='a' and ch!='s' and ch!='m' and ch!='d' and ch!='q' and ch!='\n') 
    { 
     printf("Please respond with a, s, m, d or q.\n"); 
     ch=first(); 
    } 
    return ch; 
} 
char first(void) 
{ 
    int c; 
    c=getchar(); 
    while (getchar()!='\n') 
     continue; 
    return c; 
} 
float firstn(void) 
{ 
    float first; 
    char ch; 
    printf("Enter first number:"); 
    while(scanf("%f",&first)!=1) 
    { 
     while((ch=getchar())!='\n')putchar(ch); 
      printf(" is not an number."); 
     printf("Please enter a number, such as 2.5, -1.78E8, or 3:"); 
    } 
    return first; 
} 

しかし、プログラムが実行されると、メニューはこのように2回表示されます。上記のように

Enter the operation of your choice: 
a. add   s. subtract 
m. multiply  d. divide 
q. quit 
a 
Enter first number:3 
yeah 
Enter the operation of your choice: 
a. add   s. subtract 
m. multiply  d. divide 
q. quit 
a 
Enter the operation of your choice: 
a. add   s. subtract 
m. multiply  d. divide 
q. quit 
a 
Enter first number:3 
yeah 
Enter the operation of your choice: 
a. add   s. subtract 
m. multiply  d. divide 
q. quit 

を、プログラムは最初のループで正しく動作します。それはユーザーから文字を受け取り、次に番号を要求します。しかし、2番目のループでは、プログラムが間違っています。メニューが表示されましたが、ユーザーが何を入力してもメニューには文字が表示されず、メニューが再び表示されます。メニューが2回出現した後でなければ、メニューはその文字を受け取りません。どうすればこの問題を解決できますか?

+5

今すぐにデバッガの使い方を学ぶのがよいでしょう。コードの各行を実行し、変数の値を調べます。また、コードを読み込み可能なようにインデントしてください。 – OldProgrammer

答えて

1

あなたのfirstn()関数は数字を消費しますが、最後の改行は使用しません。これは、 "(3)"の最後の改行がfirst()への次の呼び出しによって消費されることを意味します。それはオプションの1つとして認識されないので、あなたに再度質問します。

while (getchar() != '\n'); 

をごfirstn()関数の最後にだけreturn文の前に:追加

してみてください。

関連する問題