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()));//跳过空白字符