加减乘除计算器——C primer plus 5edith chapter 8

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

#include <stdio h="">
#include <stdlib h="">
#include <ctype h="">
void operation_menu();
char get_first();
float get_float();
char get_choice();
int main(void)
{
	float num1, num2;
	char ch;
	printf_s("Enter the operation of your choice:\n");
	operation_menu();
	while ((ch=get_choice())!='q')
	{
		printf_s("Enter first number:");
		num1 = get_float();
		printf_s("Enter second number:");
		num2 = get_float();
		while (ch == 'd'&&num2 == 0)
		{
			printf_s("!Please enter another number that does't include 0.\n");
			num2 = get_float();
		}
		switch (ch)
		{
		case 'a':
			printf_s("%.2f+%.2f=%.2f\n", num1, num2, (num1 + num2));
			break;
		case 's':
			printf_s("%.2f-%.2f=%.2f\n", num1, num2, (num1 - num2));
			break;
		case 'm':
			printf_s("%.2f*%.2f=%.2f\n", num1, num2, (num1*num2));
			break;
		case 'd':
			printf_s("%.2f/%.2f=%.2f\n", num1, num2, (num1 / num2));
			break;
		default:
			break;
		}
		printf_s("Enter the operation of your choice:\n");
		operation_menu();
	}
	printf_s("Bye.\n");
	system("pause");
	return 0;
}
//获取第一个字符
char get_first()
{
	int ch;
	ch = getchar();
	while (isspace(ch))
	{
		ch = getchar();
	}
	while (getchar()!='\n')
	{
		continue;
	}
	return ch;
}
//打印菜单选项
void operation_menu()
{
	printf_s("a.add               s.subtract\n");
	printf_s("m.multiply          d.divide\n");
	printf_s("q.quit\n");
}
//获取数字
float get_float()
{
	float num;
	char str[40];
	while (scanf_s("%f",&num)!=1)
	{
		gets_s(str);
		printf_s("%s is not a number.\n",str);
		printf_s("Please enter a number,such as 2.5,-1.78E8,or 3:");
	}
	while (getchar()!='\n')
	{
		;
	}
	return num;
}
//选择函数
char get_choice()
{
	char choice;
	choice = get_first();
	while (choice!='a'&&choice!='s'&&choice!='m'&&choice!='d'&&choice!='q')
	{
		printf_s("Please response with a,s,m,d or q.\n");
		choice = get_first();
	}
	return choice;
}
</ctype></stdlib></stdio>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值