《C Primer Plus》第8章 编程题 第8题

来源:互联网 发布:javascript入门书 编辑:程序博客网 时间:2024/06/13 12:38

好久没有写博客了,鄙视自己吧!

抽这个空挡学习C语言,选择的学习书籍是《C Primer Plus》。

因为时间充裕,选择了很慢的方式进行学习:看书、书上所有的例程敲上一遍、所有的课后习题来上一遍……

确实很慢,差不多两周,才整到了第八章的结束。偷笑

第8章编程题第8题,哈哈,看上去很迷信数字啊,不过确实感觉可能是前8章里难度最大的一个题。同时涵盖了前面很多的知识点,特别是第8章稍稍让人有点迷惑的“字节流”的概念,这个概念看上去不复杂,不就是逐字节的读取输入吗?!可用在程序里边还是需要适应一下。

记录下自己的方法吧。

// 显示一个菜单,提供加法、减法、乘法或除法#include <stdio.h>#include <ctype.h>// 函数原型void menu(void);// 输出菜单int get_choice(void);// 得到一个非空字符float get_number(void);// 得到一个浮点数void calc(char symbol);// 计算两个数的 + - * /int main(void){int ch;menu();// 展现菜单while((ch = get_choice()) != 'q'){switch(ch){// 根据输入选择正确的运算符或流程case 'a':calc('+');break;case 's':calc('-');break;case 'm':calc('*');break;case 'd':calc('/');break;default:printf("Please enter correct option.\n");continue;}menu();}printf("Bye.\n");return 0;}int get_choice(void){int ch;ch = getchar();while(isspace(ch))// 得到第一个非空字符ch = getchar();while(getchar() != '\n')// 跳过余下的所有字符continue;return ch;}void menu(void){printf("Enter the operation of your choice:\n");printf("a. add         s. subtract\n");printf("m. multiply    d. divide\n");printf("q. quit\n");}float get_number(void){float num;char ch;while(scanf("%f", &num) != 1){// 要求输入一个浮点数while((ch = getchar()) != '\n')// 抛弃这些非法输入并告知用户putchar(ch);printf(" is not an number.\n");printf("Please enter a number, such as 2.5, -1.78E8, or 3: ");}while(getchar() != '\n')continue;return num;}void calc(char symbol){float one, two, result;printf("Enter first number: ");// 得到运算所需的数字one = get_number();printf("Enter second number: ");two = get_number();if(symbol == '+')// 选择需要的运算result = one + two;if(symbol == '-')result = one - two;if(symbol == '*')result == one * two;if(symbol == '/'){while(two == 0){// 分母不能为 0printf("Enter a number other than 0: ");two = get_number();}result = one / two;}printf("%.2f %c %.2f = %.2f\n", one, symbol, two, result);}


原创粉丝点击