最后一题
#include <stdio.h>
char choice(void);
float first_number(void);
float second_number(void);
float add(float a,float b);
float multiply(float a,float b);
float subtract(float a,float b);
float divide(float a,float b);
int main(void)
{
float a,b;
float sum,multi,sub,div;
char ch = 0;
while((ch = choice()) != 'q')
{
a = first_number();
b = second_number();
switch(ch)
{
case 'a':
sum = add(a,b);
break;
case 'm':
multi = multiply(a,b);
break;
case 's':
sub = subtract(a,b);
break;
case 'd':
if (b == 0)
{
printf("Enter a number other than 0:");
scanf("%f",&b);
}
div = divide(a,b);
break;
}
if (ch == 'a')
printf("The sum of the two numbers is %f.\n",sum);
else if (ch == 'm')
printf("The multiply of the two numbers is %f.\n",multi);
else if (ch == 'd')
printf("The divide of the two numbers is %f.\n",div);
else if (ch == 's')
printf("The subtract of the two numbers is %f.\n",sub);
while(getchar() != '\n');
}
printf("Bye!");
return 0;
}
char choice(void)
{
char cho;
printf("Enter the operation of your choice:\n");
printf("a.add s.subtract\n");
printf("m.multiply d.divide\n");
printf("q.quit\n");
while((cho = getchar()) && cho != 'a' && cho != 'm' && cho != 's' && cho != 'd' && cho != 'q')
{
printf("Please enter again, enter a, m, s, d or q:");
while(getchar() != '\n');
}
return cho;
}
float first_number(void)
{
float first_num;
char num;
printf("Enter fisrt number:");
while(scanf("%f",&first_num) != 1) //如果输入不是数字,则scanf不会读取,会放在输入缓存等待读取,就可以用下面的getchar来读取这个字符
{
while((num = getchar()) != '\n')
putchar(num);
printf(" is not an number.\n");
printf("Please enter a number, such as 2.5, -1.78E8, or 3:");
}
return first_num;
}
float second_number(void)
{
float second_num;
char num;
printf("Enter second number:");
while(scanf("%f",&second_num) != 1)
{
while((num = getchar()) != '\n')
putchar(num);
printf(" is not an number.\n");
printf("Please enter a number, such as 2.5, -1.78E8, or 3:");
}
return second_num;
}
float add(float a,float b)
{
float sum;
sum = a + b;
return sum;
}
float multiply(float a,float b)
{
float multi;
multi = a * b;
return multi;
}
float subtract(float a,float b)
{
float sub;
sub = a - b;
return sub;
}
float divide(float a,float b)
{
float div;
div = a / b;
return div;
}