关于加减乘除的C程序求助
这个程序首先要求用户选择加/减/乘/除,如图片所示,输入d后,仍然显示要求输入a或s或m或d,相关的是char get_choice()函数,请看下问题出在哪里?#include <stdio.h>
char get_choice(); /*读取加减乘除选项*/
char get_first(); /*只读取第一个字符*/
float get_num(); /*读取要计算的数字*/
int main()
{
int choice;
float num_1,num_2;
while((choice=get_choice()) != 'q') /*期望输入字符a,s,m,d*/
{
printf("Enter first number:\n");
num_1 = get_num(); /*输入第一个数字*/
printf("Enter second number:\n");
num_2 = get_num(); /*输入第二个数字*/
switch(choice)
{
case 'a': printf("%.2f + %.2f = %.2f.\n",num_1+num_2);/*如果输入字符a,做加法*/
break;
case 's': printf("%.2f - %.2f = %.2f.\n",num_1-num_2);/*如果输入字符s,做减法*/
break;
case 'm': printf("%.2f * %.2f = %.2f.\n",num_1*num_2);/*如果输入字符m,做乘法*/
break;
case 'd': if(num_2 == 0) /*做除法,如果分母等于0,要求重新输入*/
{
printf("Please enter a number other than 0:");
while((num_2 = get_num()) == 0) /*一直输入,直到分母不等于0*/
continue;
printf("%.2f / %.2f = %.2f.\n",num_1/num_2);
break;
}
else
printf("%.2f / %.2f = %.2f.\n",num_1/num_2);
break;
default: printf("Error!\n");
break;
}
printf("Bye!.\n");
}
}
char get_choice()
{
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 = get_first();
while((ch != 'a' || ch != 's' || ch != 'm' || ch != 'd') && ch != 'q') /*如果输入的字符不等于a或s或m或d,并且不是q,那么要求重新输入*/
{
printf("Please respond with a,s,m,d or q.\n");
ch = get_first();
}
return ch;
}
char get_first()
{
int ch;
ch = getchar();
while(getchar() != '\n')
continue; /*只读取第一个字符,跳过后续字符包括回车行*/
return ch;
}
float get_num()
{
float num;
char ch;
while((scanf("%f",&num)) != 1) /*如果输入的不是数字*/
{
while((ch=getchar()) != '\n')
putchar(ch);
printf(" is not number.\n");
printf("Please input a number:\n");
}
return num;
}