//cpp 8.8题解

来源:互联网 发布:战狼2知乎 编辑:程序博客网 时间:2024/06/05 22:33






题目 :

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


一个典型的程序运行应该如下所示:

Enter the operation of your choice:

a. add s. subtract

m. multiply d. divide

q. quit

Enter first number: 22.4

Enter second number: one

one is not an number.

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

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: 0

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.


需求分析 :

  • 只接受它提供的菜单选项;
  • 接受float类型的数字;
  • 输入字母的函数:只接受第一个首字母,其他字母丢弃

    注意换行符的消去

  • 输入数字的函数:如果不上是数字允许重新输入
  • 注意除法的要求;

    如果是0,提示用户继续输入第二个数字


#include stdio.h#include ctype.hfloat get_float(void);char get_first(void);int main(int argc, char const *argv[]){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:\n");num1 = get_float();printf("Enter second number:\n");num2 = get_float();while (select == 'd' && num2 == 0){printf("Enter a number other than 0:\n");num2 = get_float();}switch (select){case 'a': printf("%.2f + %.2f = %.2fn\n", num1, num2, num1 + num2); break;case 's': printf("%.2f - %.2f = %.2fn\n", num1, num2, num1 - num2); break;case 'm': printf("%.2f * %.2f = %.2fn\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.1 or 3.11\n");}while (getchar() != '\n');return num;}char get_first(void)//得到字符串中的第一个字符,滤去其他字符{int ch;while (isspace(ch = getchar()));while (getchar() != '\n');return ch;}`


1 0