算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4
的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4
。请设计程序计算前缀表达式的结果值。
输入格式:
输入在一行内给出不超过30个字符的前缀表达式,只包含+
、-
、*
、\
以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式:
输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR
。
输入样例:
+ + 2 * 3 - 7 4 / 8 4
输出样例:
13.0
#include<iostream>
#include<vector>
#include<cstdio>
#include<set>
#include<map>
#include<string>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<stdlib.h>
#include<ctype.h>
#include<stack>
#include<queue>
#include<list>
using namespace std;
stack<double>st1;
int main(){
char c;
char ch[20005];
int i=0,cc=1;
while((c=getchar())!= '\n'){
ch[i++] = c;
}
for(int j=i-1; j>=0; j--){
if(ch[j]==' ')
continue;
if(ch[j]>='0' && ch[j]<='9'){
double mul = 10, num = ch[j] - '0';
for (j--; j >= 0; j--)
{
if (ch[j]>='0' && ch[j]<='9')
{
num += (ch[j] - '0') * mul;
mul *= 10;
}
else if (ch[j] == '.')
{
num /= mul;
mul = 1;
}
else if (ch[j] == '-')
num = -num;
else
break;
}
st1.push(num);
}
else{
double temp = st1.top();
st1.pop();
if(ch[j]=='*'){
temp *= st1.top();
st1.pop();
}
else if(ch[j]=='/'){
if(st1.top()==0){
cout<<"ERROR"<<endl;
return 0;
}
temp /= st1.top();
st1.pop();
}
else if(ch[j]=='+'){
temp += st1.top();
st1.pop();
}
else{
temp -= st1.top();
st1.pop();
}
st1.push(temp);
}
}
printf("%.1lf",st1.top());
return 0;
}
思路: 首先,我们想问题要全面,度提要仔细!!!
1、题目中没有明确说明是整数,而且也没说是正数,所以我们必须考虑 小数 和 负数 的情况 !
2、因为是按字符输入,例如小数3.2 的格式为3.2,这里‘.’的前后是没有空格的!我们读取从右至左,所以会先读到2然后是‘.’,最后是3;我们只需要让2变成0.2;加上3就搞定了!!!
3、负数:例如-1 格式是就是-1 中间也没有空格;有空格一定是-。我们遍历时如果遇到数字和‘-’挨着,那么就一定是负数!!!
4、这两种特殊数据处理完就按照计算前缀表达式的正常的步骤处理就ok;