HDU-1237

来源:互联网 发布:男士保湿面霜知乎 编辑:程序博客网 时间:2024/05/21 08:39

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

Input

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

Output

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

Sample Input

1 + 2

4 + 2 * 5 - 7 / 11

0

Sample Output

3.00

13.36


思路:

加减乘除可用栈来做,此题有点注意的是要读取空格。


代码如下:

#include<iostream>#include<cstring>#include<string>#include<stack>#include<algorithm>#include<cstdio>using namespace std;int main(){double n, temp; char b; char c[2];while (scanf("%lf%c",&n,&b)){if (n == 0 && b == '\n')break;      //程序结束条件double ans = 0;stack<double>s;                     //声明栈s.push(n);//压进栈while (scanf("%s %lf",c,&n)!=EOF)   //字符串c读取符号与一个空格{if (c[0] == '+')s.push(n);       else if (c[0] == '-')s.push(-n);else if (c[0] == '*')   //取出栈顶元素进行运算{temp = n*s.top();     s.pop();s.push(temp);}else                    //取出栈顶元素进行运算{temp = s.top() / n;s.pop();s.push(temp);}if (b = getchar(), b == '\n')break;    //读取一个空格}while (!s.empty())   //此时栈中的元素是正或者负 只需相加即可 {ans += s.top();s.pop();}printf("%.2lf\n", ans);  }return 0;}



原创粉丝点击