题目
答案
#include<stdio.h>
#include<stack>
#include<math.h>
#include<string>
#include<iostream>
using namespace std;
int main()
{
string a[100];
int n=0,i,flag=0;
stack<double> s;
while(cin>>a[n++]){}
n--;
for(i=n-1;i>=0;i--)
{
if(a[i].length()==1&&(a[i][0]=='+'||a[i][0]=='-'||a[i][0]=='*'||a[i][0]=='/'))
{
if(s.size()<2)
{
flag=1;break;
}
double tmp1=s.top();s.pop();
double tmp2=s.top();s.pop();
if(a[i][0]=='+') s.push(tmp1+tmp2);
else if(a[i][0]=='-') s.push(tmp1-tmp2);
else if(a[i][0]=='*') s.push(tmp1*tmp2);
else if(a[i][0]=='/')
{
if(tmp2==0)
{
flag=1;break;
}
else s.push(tmp1/tmp2);
}
}
else
{
double tmp=atof(a[i].c_str());
s.push(tmp);
}
}
if(s.size()!=1) flag=1;
if(flag) printf("ERROR");
else printf("%.1f",s.top());
}
注意
(本题我参考了这篇文章:
https://blog.csdn.net/weixin_42104573/article/details/80431862)
- n要记得减1,这个目前我也没完全搞懂,只能先理解为输入时将回车也吸收了,所以要减1
if(a[i].length()==1
的作用就是防止把负数的负号误认为是减号 ,比如你输入-1,但如果没有判断长度,减号就会被误认为是负号和数字1,导致程序错误。- 熟练使用atof和c_str函数,能帮助大家高效解题——c_str() 函数是转化为字符数组 ,而atof() 是c语言中将字符数组转化为浮点型数据函数(atof是math.h库中的函数)