源代码:
- #include <stdio.h>
- 2 #include <ctype.h>
- 3 char get_first(void);
- 4 char get_choice(void);
- 5 float get_float(void);
- 6 int main(void)
- 7 {
- 8 int choise;
- 9 float num1;
- 10 float num2;
- 11
- 12 while((choise = get_choice()) != 'q')
- 13 {
- 14 switch(choise)
- 15 {
- 16 case 'a' : printf("a\n");
- 17 printf("Enter first number:");
- 18 num1 = get_float();
- 19 printf("Enter second number:");
- 20 num2 = get_float();
- 21 printf("%.1f + %.1f = %.1f\n",num1,num2,num1 + num2);
- 22 break;
- 23 case 's' : printf("b\n");
- 24 printf("Enter first number:");
- 25 num1 = get_float();
- 26 printf("Enter second number:");
- 27 num2 = get_float();
- 28 printf("%.1f - %.1f = %.1f\n",num1,num2,num1 - num2);
- 29 break;
- 30 case 'm' : printf("m\n");
- 31 printf("Enter first number:");
- 32 num1 = get_float();
- 33 printf("Enter second number:");
- 34 num2 = get_float();
- 35 printf("%.1f * %.1f = %.1f\n",num1,num2,num1 * num2);
- 36 break;
- 37 case 'd' : printf("d\n");
- 38 printf("Enter first number:");
- 39 num1 = get_float();
- 40 printf("Enter second number:");
- 41 num2 = get_float();
- 42 printf("%.1f / %.1f = %.1f\n",num1,num2,num1 / num2);
- 43 break;
- 44 default : printf("Program error!\n");
- 45 break;
- 46 }
- 47 }
- 48 printf("Bye!\n");
- 49 return 0;
- 50 }
- 51
- 52 char get_choice(void)
- 53 {
- 54 int ch;
- 55
- 56 printf("Enter the operation of your choice:\n");
- 57 printf("a.add s.subtract\n");
- 58 printf("m.multiply d.divide\n");
- 59 printf("q.quit\n");
- 60
- 61 ch = get_first();
- 62 while((ch != 'a') && (ch != 's') && (ch != 'm') && (ch != 'd') && (ch != 'q') )
- 63 {
- 64 printf("Please respond with a,s,m,d,q.\n");
- 65 ch = get_first();
- 66 }
- 67 return ch;
- 68
- 69 }
- 70
- 71 /*char get_first(void)
- 72 {
- 73 int ch;
- 74
- 75 ch = getchar();
- 76 while(getchar() != '\n')
- 77 continue;
- 78 return ch;
- 79 }*/
- 80
- 81
- 82
- 83 char get_first(void)
- 84 {
- 85 int ch;
- 86
- 87 ch = getchar();
- 88 while(isspace(ch))
- 89 ch = getchar();
- 90 while(getchar() != '\n')
- 91 continue;
- 92 return ch;
- 93 }
- 94
- 95
- 96 float get_float(void)
- 97 {
- 98 float input;
- 99 char ch;
- 100
- 101 while(scanf("%f",&input) != 1)
- 102 {
- 103 while((ch = getchar()) != '\n')
- 104 putchar(ch);
- 105 printf(" is not an number.\n");
- 106 printf("Please enter a number, such as 2.5, -1.78E8, or 3:");
- 107 }
- 108 return input;
- 109 }
- 110
运行效果:
:!gcc test8.c -o test8 :! ./test8 Enter the operation of your choice: a.add s.subtract m.multiply d.divide q.quit s b Enter first number:3 Enter second number:5 3.0 - 5.0 = -2.0 Enter the operation of your choice: a.add s.subtract m.multiply d.divide q.quit m m Enter first number:4567 Enter second number:789 4567.0 * 789.0 = 3603363.0 Enter the operation of your choice: a.add s.subtract m.multiply d.divide q.quit q Bye! |