普通计算器的实现

时间:2022-02-06 19:00:47
 1 #include<stdio.h>
 2 #include<conio.h>
 3 #include<stdlib.h>
 4 float get_answer()/*定义求结果的函数*/
 5 {
 6     float a,b,answer;
 7     char flag;
 8     scanf("%f%c%f",&a,&flag,&b);
 9     switch(flag)
10     {
11     case '+': answer=a+b;break;
12     case '-': answer=a-b;break;
13     case '*': answer=a*b;break;
14     case '/': answer=a/b;break;
15     }
16     return answer;
17 }
18 void main()/*主函数*/
19 {
20     float b,answer;
21     char flag;
22     int point;
23     system("title 普通计算器");
24     system("color f0");
25     printf("输入要保留的小数位:");
26     scanf("%d",&point);
27     printf("就绪!过程中按“Esc”退出!\n");
28     answer=get_answer();
29     printf("=%.*f\n",point,answer);
30     while(1)
31     {
32         flag=getch();/*检测将要执行的命令*/
33         if(flag==42||flag==43||flag==45||flag==47)/*判断是否是“+,-,*,/”*/
34         {printf("%c",flag);/*输出运算符*/
35         scanf("%f",&b);
36         switch(flag)
37         {
38         case '+': answer+=b;break;
39         case '-': answer-=b;break;
40         case '*': answer*=b;break;
41         case '/': answer/=b;break;
42         }
43         printf("%.*f",point,answer);}
44         else if(flag==27)/*按Esc退出*/
45             break;
46         else/*再次执行运算*/
47         {
48             printf("\n请输入“a+、-、*、/、b”:\n");
49             answer=get_answer();
50             printf("=%.*f\n",point,answer);
51         }
52     }
53 }