PTA 后缀式求值
希望看到博客的同学能够告诉我为什么一个200的数组装得下的数据,一个栈装不下
我们人类习惯于书写“中缀式”,如 3 + 5 * 2 ,其值为13。 (p.s. 为什么人类习惯中缀式呢?是因为中缀式比后缀式好用么?)
而计算机更加习惯“后缀式”(也叫“逆波兰式”,Reverse Polish Notation)。上述中缀式对应的后缀式是:
3 5 2 * +
现在,请对输入的后缀式进行求值。
输入格式:
在一行中输入一个后缀式,运算数和运算符之间用空格分隔,运算数长度不超过6位,运算符仅有+ - * / 四种。
输出格式:
- 在一行中输出后缀式的值,保留一位小数。
输入样例:
- 3 5.4 2.2 * +
输出样例:
- 14.9
第一个点老是过不去,像我一下这样写,我很不解:
#include <bits/stdc++.h>
using namespace std;
float a[200];
float oper(float n1,float n2,string s)
{
if(s=="+")
{
return n1+n2;
}else if(s=="-")
{
return n1-n2;
}else if(s=="*")
{
return n1*n2;
}else if(s=="/")
{
return n1/n2;
}
}
int main()
{
int top=0;
string s;
cin >> s;
float n;
n=atof(s.c_str());
a[top]=n;
char ch=getchar();
while(ch!='\n')
{
if(s=="+"||s=="-"||s=="*"||s=="/")
{
float num1=a[top];
top--;
float num2=a[top];
float num3=oper(num2,num1,s);
a[top]=num3;
}else
{
top++;
float num;
num=atof(s.c_str());
a[top]=num;
}
cin >> s;
ch=getchar();
}
if(s=="+"||s=="-"||s=="*"||s=="/"&&top==1)
{
float num1=a[top];
top--;
float num2=a[top];
float num3=oper(num2,num1,s);
a[top]=num3;
}
printf("%0.1f",a[top]);//这玩意会自动四舍五入 ,厉害了。14.88 保留一位小数 14.9 !!!!!
}
已经要放弃了
但是
:
我没有放弃,历经4五个小时之后,我成功了:
#include <bits/stdc++.h>
using namespace std;
double a[200];//为什么用数组而不直接用堆栈呢?因为测试样例的数据 栈 装不下,会段错误。
double oper(double n1,double n2,char s)
{
if(s=='+')
{
return n1+n2;
}else if(s=='-')
{
return n1-n2;
}else if(s=='*')
{
return n1*n2;
}else if(s=='/')
{
return n1/n2;
}
}
int main()
{
int top=0;
string s;
getline(cin,s);
for(int i=0;i<s.size();i++)
{
if((s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')&&(s[i+1]==' '||i==s.size()-1))//我在这里卡了半天,没有考虑到负数的情况会在这里产生影响。
{
double num1=a[--top];
top--;
double num2=a[top];
double num3 = oper(num2,num1,s[i]);
a[top]=num3;
top++;
}else if(s[i]==' ')
{
continue;
}else
{
string str="";
while(s[i]!=' ')
{
str+=s[i];
i++;
}
double num=atof(str.c_str());
a[top]=num;
top++;
}
}
printf("%.1f",a[--top]);
}
**//希望看到博客的同学能够告诉我为什么一个200的数组装得下的数据,一个栈装不下**