首页 > 试题广场 >

编写一个程序,显示一个菜单,为您提供加法、减法、乘法或除法的

[问答题]

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

Enter the operation of your choice:

a. add       s. subtract

m. multiply   d. divide

q. quic

Enter first number: 22.4

Enter second number: one

one is not an number.

Please enter a number, such as 2.5. -1.78E8, or 3. 1

22.4 + 1 = 23.4

Enter the operation of your choice:

a. add        s. subtract

m. multiply   d. divide

q. quit

Enter first number: 18.4

Enter second number: O

Enter a number other than 0: 0.2

18.4 / 0.2 = 92

Enter the operation of your choice:

a. add        s. subtract

m. multiply   d. divide

q. quit

q

Bye.

推荐
#include<stdio.h>
#include<ctype.h>
float get_float(void);
char get_first(void);
int main(void)
{
 char select;
 float num1,num2;
 while(1)
 {
 printf("Enter the operation of your choice:\n");
 printf("a.add            s.subtract:\n");
 printf("m.multiply       d.divide\n");
 printf("q.quit\n");
 select = get_first();
 if( select != 'a' && select != 's' && select != 'm' && select != 'd')
 {
 printf("Bye.\n");
 break;
 }
 printf("Enter first number:");
 num1 = get_float();
 printf("Enter second number:");
 num2 = get_float();
 while( select == 'd' && num2 == 0) 
 {
 printf("Enter a number other than 0:");
 num2 = get_float();
 }
 switch(select)
 {
 case 'a': printf("%.2f + %.2f = %.2f\n",num1, num2, num1 + num2); break;
 case 's': printf("%.2f - %.2f = %.2f\n",num1, num2, num1 - num2); break;
 case 'm': printf("%.2f * %.2f = %.2f\n",num1, num2, num1 * num2); break;
 case 'd': printf("%.2f / %.2f = %.2f\n",num1, num2, num1 / num2); break;
 default : break;
 }
 }
 return(0);
}
float get_float(void) //得到一个合适的浮点数,滤除非法数
{
 float num;
 char str[40];
 while(scanf("%f",&num)!=1)
 {
 gets(str);
 printf("%s is not a number.\n",str);
 printf("Please enter a numbe, such as 2.5, -1.78E8, or 3:");
 }
 while ( getchar() != '\n');
 return num;
}
char get_first(void) //得到字符串中的第一个字符,滤除其他字符
{
 int ch;
 while( isspace( ch = getchar() ) );
 while ( getchar() != '\n');
 return ch;
}

发表于 2018-05-05 21:43:05 回复(0)