编写一个程序,显示一个菜单,为您提供加法、减法、乘法或除法的选项,获得您的选择后,该程序请求两个数,然后执行您选择的操作,该程序应该只接受它所提供的菜单选项,它应该使用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>