第一次输入没问题,第二次的时候局部变量choice为”\n" 然而代码中已经使用了while((ch = getchar())!='\n')
完整代码如下:
#include<stdio.h>
char menu(void);
void af(char n);
double inp2(void);
int main(void)
{
char choice;
choice = menu();
while(choice != 'q')
{
switch(choice)
{
case 'a':
af('a');
break;
case 's':
af('s');
break;
case 'm':
af('m');
break;
case 'd':
af('d');
break;
//default:
// printf("Please enter a valid letter,such as a,s,m or d:");
}
choice = menu();
}
return 0;
}
char menu(void)
{
printf("Enter the operation of your choice:\n");
printf("a.ad s.subtract\n");
printf("m.multiply d.divide\nq.quit\n");
char choice;
scanf("%c",&choice);
char ch;
while((ch = getchar()) != '\n')
continue;
return choice;
}
void af(char n)
{
printf("Enter first number:");
double a;
a = inp2();
printf("Enter second number:");
double b;
b = inp2();
while(n == 'd' && b == 0)
{
printf("Enter a number other than 0:");
b = inp2();
}
if(n == 'a')
printf("%g + %g = %g\n",a,b,a+b);
else if(n == 's')
printf("%g - %g = %g\n",a,b,a-b);
else if(n == 'm')
printf("%g * %g = %g\n",a,b,a*b);
else if(n == 'd')
printf("%g / %g = %g\n",a,b,a/b);
}
double inp2(void)
{
double num;
if(scanf("%lf",&num) != 1)
{
char ch;
while((ch = getchar()) != '\n')
putchar(ch);
printf(" is not an number.\n");
printf("Please enter a number, such as 2.5,-1,78E8,or3:");
num = inp2();
}
return num;