Advanced Experiment 3-3.1 seeking prefix value of the expression (25 points)
Arithmetic expression notation prefix, infix and postfix notation representation method. A binary operator prefix expression means located before the two operands, e.g. prefix expression 2 + 3 * (7-4) +8/4 is: 2 + + * 3--74 / 84. Please design program calculates the result of the expression prefix value.
: Input format
separated by a space, *, /, and calculating the number of different objects (operand, the arithmetic sign) - input is given no more than 30 characters in a line prefix expression that contains only +.
Output format:
calculation result output prefix expression, retaining a decimal or an error message ERROR.
Sample input:
+ 2 * 3--74 / 84
Sample output:
13.0
Expression from right to left scanning, while a numeral, the number onto the stack, the face of the operator, playing a stack of two numbers, using operators calculated accordingly (the top element of the op-top thereof elements), and the result stack; repeat the process until the leftmost expression, is the value obtained by the last calculation result of the expression.
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<int>s1;
stack<char>s2;
char ch;
ch=getchar();
while(ch!='\n'){
if(ch!=' '){
//cout<<"check001:"<<s2.top()<<endl;}
s2.push(ch);}
ch=getchar();
}
int x=0,y=0,z=0,a=0;
char ca;
while(s2.size()){
ca=s2.top();s2.pop();
if(ca!='+'&&ca!='-'&&ca!='*'&&ca!='/'){
a=static_cast<int>(ca)-48; //字符数字转化为int类型的数字
s1.push(a);
//cout<<"check002:"<<s1.top()<<endl;
}
else{
x=s1.top();s1.pop();
y=s1.top();s1.pop();
if(ca=='+'){z=x+y;}
else if(ca=='-'){z=x-y;}
else if(ca=='*'){z=x*y;}
else if(ca=='/'){z=x/y;}
s1.push(z);
}
if(s2.empty()){
cout<<s1.top()<<endl;//----->13
}
}
return 0;
}