传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1237
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36
//这个比较通俗易懂,参考大佬博文。加深stack运用的理解
#include<iostream>
#include<cstdio>
#include<stack>
#include<algorithm>
using namespace std;
int n;
int main(){
char c;
stack<double>st;
double sum,m;
while(cin>>n){
sum=0;
c=getchar();
if(c=='\n'&&n==0)break;//此时表示只输入了一个0
st.push(n);
cin>>c;
while(cin>>n){
if(c=='+'){
st.push(n);//直接放进栈
}
else if(c=='-')
st.push(-n);//直接放进栈
else if(c=='*'){
m=st.top();//拿出栈顶的值进行乘法运算
m*=n;//计算乘的值,放入栈中
st.pop();//弹出原来的栈顶的值
st.push(m);
}
else if(c=='/'){
m=st.top();
m/=n;//计算除的值,在放入栈中
st.pop();
st.push(m);
}
if(getchar()=='\n'){//判断输出结束换行
break;}
cin>>c;//读入运算符号
}
while(!st.empty()){
double key=st.top();
sum+=key;
st.pop();
}
printf("%.2f\n",sum);
}
return 0;
}
模拟一下