概述
最后一题
#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.subtractn");
printf("m.multiply
d.dividen");
printf("q.quitn");
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;
}
最后
以上就是酷酷麦片为你收集整理的C Primer Plus第六版 第八章编程练习的全部内容,希望文章能够帮你解决C Primer Plus第六版 第八章编程练习所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复