8章8题

8、编写一个程序,显示一个菜单,为您提供加法,减法,乘法或除法的选项。获得您的选择后,该程序请求两个数,然后执行您选择的操作。该程序应该只接受它所提供的菜单选项。它应该使用float类型的数,并且如果用户未能输入数字应允许重新输入。在除法的情况下,如果用户输入0作为第二个数,该程序应该提示用户输入一个新的值,


#include <stdio.h>
#include <stdlib.h>
#include<ctype.h>

float get_int(void); //输入数字函数
char get_choice(void );//选择菜单函数
char get_first(void); //输入菜单选项函数
void add(void);	//加法函数
void sub(void);	//减法函数
void mul(void);//乘法函数
void divi(void); //除法函数

int main()
{
	int choice;
	while((choice=get_choice())!='q')
	{
		switch(choice)
		{
			case 'a': add();
			break;
			case 's': sub();
			break;
			case 'm': mul();
			break;
			case 'd': divi();
			break;
			default: break;

		}
	}
	printf("BYE\n");
	return 0;
}

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()
{
	char ch;
	while(isspace(ch=getchar()));//跳过空白字符
	return ch;
}
float get_int()
{
	float input;
	char ch;
	//如果输入的是非数字字符的话。则剔除它,重新输入
	while(scanf("%f",&input)!=1)
	{
		while((ch=getchar())!='\n')
			putchar(ch);
		printf(" is not a number.\nplease enter a ");
		printf("number,such as 2.5,-1.78E8,or 3:");
	}
	return input;
}
void add()
{
	float a,b;
	printf("Enter first number:");
	a=get_int();
	printf("Enter second number:");
	b=get_int();
	printf("%.1f+%.1f=%.1f\n",a,b,a+b);
}

void sub()
{
	float a,b;
	printf("Enter first number:");
	a=get_int();
	printf("Enter second number:");
	b=get_int();
	printf("%.1f-%.1f=%.1f\n",a,b,a-b);
}

void mul()
{
	float a,b;
	printf("Enter first number:");
	a=get_int();
	printf("Enter second number:");
	b=get_int();
	printf("%.1f*%.1f=%.1f\n",a,b,a*b);
}

void divi()
{
	float a,b;
	printf("Enter first number:");
	a=get_int();
	printf("Enter second number:");
	b=get_int();
	if(b==0)
	{
		printf("Enter a number other than o:");
		b=get_int();
	}
	printf("%.1f/%.1f=%.1f\n",a,b,a/b);
}


这个程序最主要的地方就在于怎么控制输入结束后的换行符的解决,如果程序不把换行符去掉的话程序就运行不了,

while(isspace(ch=getchar()));//跳过空白字符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值