版权声明:小媛原创,转载请注明出处! https://blog.csdn.net/xingfushiniziji/article/details/85928641
hdu 1237 简单计算器(栈)
如果是+,就把原数压入栈
如果是-,就把相反数压入栈
如果是*,就把当前数和栈顶数计算后压入栈
如果是/,就把当前数和栈顶数计算后压入栈
注意该题是3 + 2而不是3+2,有空格
#include <iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<stack>
using namespace std;
stack<double> num;
int main()
{
int n;
while(scanf("%d",&n)){
char c;
c=getchar();//注意中间有空格,接收空格
if(c=='\n'&&n==0)//当输入为0
break;
double sum=0,temp;
num.push(n);//把n入栈;
c=getchar(); //接受+-*/
while(scanf("%d",&n)){
if(c=='*'){
temp=num.top();
temp*=n;
num.pop();//把原来的弹出
num.push(temp);//把乘积计算好的入栈
}
else if(c=='/'){
temp=num.top();
temp/=n;
num.pop();
num.push(temp);
}
else if(c=='+')
num.push(n);
else if(c=='-')
num.push(0-n);
if(getchar()=='\n')//本行输入结束
break;
c=getchar();//如果这行输入没有结束就接着接受空格
}
while(!num.empty()){
sum+=num.top();
num.pop();
}
printf("%.2lf\n",sum);
}
return 0;
}