openjudge169 Prefix expression evaluation
Time limit 1000MS/64MB Description
An inverse Polish expression is an arithmetic expression that puts an operator in front of it, such as a normal expression 2 + 3 with an inverse Polish representation of + 2 3. The advantage of the inverse Polish expression is that the operators do not have to have a precedence relationship, and do not have to use parentheses to change the order of operations, for example (2 + 3) * 4 of the inverse Polish notation for * + 2 3 4. This solves the value of the inverse Polish expression, where the operator includes +-*/four. Input
Enter as a row, where the operators and operands are separated by a space, and the operand is a floating-point number. Output
Output is a row, the value of the expression.
The value V of an expression can be output directly with printf ("%f\n", V). Sample input
* + 11.0 12.0 + 24.0 35.0
Sample output
1357.000000
Tips
You can use Atof (str) to convert a string to a floating-point number of type double. Atof is defined in MATH.H.
This topic can be solved by using the method of recursive function calls.
Analysis
Prefix expression evaluation: From left to right scan expression, when a number is encountered, the number is pressed onto the stack, the number of two digits on the top of the pop-up stack when the operator is encountered, the corresponding calculation is done with the operator (the top element of the secondary top element operator stack), and the result is placed on the stack, repeating the process to the right end The value of the last operation is the result of an expression.
Here you can use the conditions given in the title, using the Stof function and the recursive return solution.
Code
#include <iostream>
#include <cstring>
#include <cctype>
#include <cmath>
using namespace std;
Char s[5000];
Double Solve () {
cin>>s;
int Len=strlen (s); String length
if (len==1 &&!isdigit (s[0)) //length 1 and first not digital
switch (s[0) {case
' + ': return solve () +solve ();
Case '-': Return Solve ()-solve ();
Case ' * ': Return Solve () *solve ();
Case '/': Return Solve ()/solve ();
}
else return atof (s); Converts a string to a numeric value
}
int main () {
printf ("%f\n", Solve ());
return 0;
}