69,371
社区成员
发帖
与我相关
我的任务
分享
Enter first number: 18.4
Enter second number: 0
Enter a number other than 0: 0.2
18.4 / 0.2 = 92
#include<stdio.h>
void add(void);
void div(void);
float get_float(void);
char get_choice(void);
char get_first(void);
float get_zero(void);
int main(void)
{
char choice;
while((choice = get_choice()) != 'q')
{
switch(choice)
{
case 'a':add();
break;
case 'b'://subtract();
break;
case 'c'://multiply();
break;
case 'd':div();
break;
case 'q':printf("quit");
break;
}
}
printf("Bye.\n");
return 0;
}
char get_choice(void)
{
int ch;
printf("Enter the letter of your choice:\n");
printf("a. add b. subtract\n");
printf("c. multiply d. divide\n");
printf("q. quit\n");
ch = get_first();
while ((ch < 'a' || ch > 'd') && ch != 'q')
{
printf("Please respond with a, b, c, d, or q.\n");
ch = get_first();
}
return ch;
}
char get_first(void)
{
int ch;
ch = getchar();
while (getchar() != '\n')
continue;
return ch;
}
void add(void)
{
float x, y;
printf("Enter first number: ");
x = get_float(); //需要检测下没有这里的语句可否通过
printf("Enter second number: ");
y = get_float();
while (getchar() != '\n')
continue;
printf("%.1f + %.f = %.1f\n", x, y, x + y);
}
void div(void)
{
float x, y;
printf("Enter first number: ");
x = get_float();
printf("Enter second number: ");
y = get_zero();
while(getchar() != '\n')
continue;
printf("%.1f / %.1f = %.1f\n", x, y, x / y);
}
float get_zero(void)
{
float input;
/*while(scanf("%f", &input) != 1)
{
while(putchar(input) == 0)
printf("Enter a number other than 0: ");
break;
}
return input;*/
scanf("%f", &input);
if(input == 0)
printf("Enter a number other than 0: \n");
else
return input;
}
float get_float(void)
{
float input;
char ch;
while (scanf("%f", &input) != 1)
{
while ((ch = getchar()) != '\n')
putchar(ch); // dispose of bad input
printf(" is not a number.\nPlease enter a ");
printf("number, such as 2.5, -1.78E8, or 3: ");
}
return input;
}
float get_zero(void)
{
float input;
scanf("%f", &input);
while(input ==0)
{
printf("Enter a number other than 0: ");
scanf("%f", &input);
}
return input;
}
float get_zero(void)
{
float input;
/*while(scanf("%f", &input) != 1)
{
while(putchar(input) == 0)
printf("Enter a number other than 0: ");
break;
}
return input;*/
scanf("%f", &input);
if(input == 0){
printf("Enter a number other than 0: \n");
return get_zero();
}
else
return input;
}