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回出現した後でなければ、メニューはその文字を受け取りません。どうすればこの問題を解決できますか?
今すぐにデバッガの使い方を学ぶのがよいでしょう。コードの各行を実行し、変数の値を調べます。また、コードを読み込み可能なようにインデントしてください。 – OldProgrammer