C语言下的简易计算器

 1 #include <stdio.h>
 2 #include <math.h>
 3 int main()
 4 {    
 5     double data1, data2;
 6     char op;
 7     while (3 == scanf("%lf%c%lf", &data1, &op, &data2) )
 8         { 
 9             double result;
10             printf("%lf%c%lf=", data1,data2);
11             switch (op)
12             {
13                 case '+':
14                 result = data1 + data2;
15                 break;
16                 case '-':
17                 result = data1 - data2;
18                 break;    
19                 case '*':
20                 result = data1 * data2;
21                 break;    
22                 case '/':          
23                 result = data1 / data2;
24                 break;      
25                 default:;
26             }        
27             printf("%lf\n", result);    
28         }    
29 
30     return 0;
31 }

↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓7.18更新↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

说明:上面的代码在计算特定运算时会出现舍入错误,原因待定,修改代码如下解决。

 1 #include <stdio.h>
 2 int main()
 3 {    
 4     float data1, data2;
 5     char op;
 6     while (3 == scanf("%f%c%f", &data1, &op, &data2) )
 7         { 
 8             float result;
 9             printf("%f%c%f=", data1, op, data2);
10 
11             switch (op)
12             {
13                 case '+':
14                 result = data1 + data2;
15                 break;
16                 case '-':
17                 result = data1 - data2;
18                 break;    
19                 case '*':
20                 result = data1 * data2;
21                 break;    
22                 case '/':          
23                 result = data1 / data2;
24                 break;      
25                 default:;
26             }        
27             printf("%f\n", result);    
28         }    
29 
30     return 0;
31 }

 

posted @ 2014-06-20 14:00  rhinoc  阅读(561)  评论(0编辑  收藏  举报