/* The value of the prefix expression (25) time limit MS Memory limit 65536 KB code length limit 8000 B program standard arithmetic expression prefix notation, infix notation and suffix notation prefix expression refers to the two-dollar operator before two operands, for example 2+3* (7-4) The prefix expression for +8/4 is: + 2 * 3-7 4/8 4 Please design the program to calculate the result value of the prefix expression. Input Format Description: Enter the prefix expression of no more than 30 characters in a row, containing only the + 、-、 *, \ and the number of operands, different objects (operands, operators) separated by a space-delimited output format description: Output prefix expression of the results, accurate to 1 digits after the decimal point, or error message "error" Sample input and output: Serial number input/output 1 + + 2 * 3-7 4/8 4 13.02/-25 + *-2 3 4/8 4 12.53/5 + *-2 3 4/8 2 ERROR4 +10.23 10.2 Analysis: 1) Put all elements in the queue, such as a symbol followed by two numbers, drop the symbol and two number, and put the result in the symbol position 2) Round trip, until the end only one element, Output 3) calculated as error, output error and return, if the result is correct output when the result retains a decimal place/#include <iostream> #include <string># include<sstream> #include <cstdlib>//GCVT or Sprintf#include<iomanip>using namespace std;double Calcult (String op, double A, double b) {switch (op[0]) {case ' + ': return a + B; Case '-': return a-B; Break Case ' * ': return a * b; Break Case '/': return a/b; Break }}void Input (String q[], int& i) {string line,str; GetLine (CIN, line, ' \ n '); Istringstream stream (line); i = 0; This step has the positive sign removed before the plus while (Stream >> str) {q[i++] = str; }}bool Isoper (string& Item) {return (item = = "+" | | item = "-" | | item = "*" | | item = "/")? True:false;} void Getval (String q[], int len) {double A, B; String op; Char val[20]; while (Len > 1) {for (int i = 0; i < len; ++i) {if (Isoper (Q[i])) { if (i + 2 < len &&!) Isoper (Q[i + 1]) &&! Isoper (Q[i + 2])) {op = q[i]; A = strtod (Q[i + 1].c_str (), NULL); b = strtod (Q[i + 2].c_str (), NULL); if (op = = "/" && b = = 0) {cout << "ERROR" << Endl; Return } for (int j = i+1; j < len-2; ++j) Q[j] = q[j + 2]; Len-= 2; Linux can not be used sprintf_s, and can not be used _gcvt_s,//And GCVT (floating point value, A, Val); Where 15 is the number of significant digits//buffer, buffer size (minus 1 bits, save Terminator?), floating-point number, significant digits (max.) _gcvt_s (Val, B, Calcult (OP, a , b), 17); Q[i] = val; }}}} cout << setiosflags (ios::fixed) << setprecision (1) << strtod ( Q[0].c_str (), NULL) << Endl; }void Run () {string q[30]; int Len; Input (Q,len); Getval (Q,len);} int main (void) {Run (); return 0;}
To find the value of a prefix expression