F

Description

读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。 
 

Input

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。 
 

Output

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。 
 

Sample Input

1 + 2
4 + 2 * 5 - 7 / 11 0
 

Sample Output

3.00
13.36
 
分析:可以用栈解决,也可以用数组解决,栈还不是很会,所以我是用数组做的,以后再将栈的做法补上。
 
思路:我的思路就是首先考虑乘除,就是将两个要进行乘除运算的数计算出来看作是一个数。实际操作就是你将每一次加法和减法前数的总和保存在数组中,将输入的数赋给另一个变量,留待乘除调用。最后重新定义一个变量记录最后的结果, 将所有值依次相加。
 
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 double sum;
 6 double ans[211];
 7 char c;
 8 int main()
 9 {
10     int t,n;
11     while(scanf("%d",&t)!=EOF)
12     {
13         n=0;
14         sum=t*1.0;//又是初始值定义错误
15         if(t==0&&(c=getchar())=='
')//这里要注意一下
16             return 0;
17         while((c=getchar())!='
')
18         {
19             if(c=='*')
20             {
21                 scanf("%d",&t);
22                 sum*=t*1.0;
23             }
24             if(c=='/')
25             {
26                 scanf("%d",&t);
27                 sum/=t*1.0;
28             }
29             if(c=='+')
30             {
31                 ans[n++]=sum;
32                 scanf("%d",&t);
33                 sum=t*1.0;//将输入的数保存,以便用于乘除运算
34             }
35             if(c=='-')
36             {
37                 ans[n++]=sum;
38                 scanf("%d",&t);
39                 sum=-t*1.0;
40             }
41         }
42         ans[n++]=sum;
43         double cnt=0;
44         for(int i=0; i<n; i++)
45             cnt+=ans[i];
46         printf("%.2lf
",cnt);
47     }
48     return 0;
49 }
View Code
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/lbyj/p/5676072.html