NYOJ128 prefix computing (stack Application)
The value of + 2 * + 3 4 5 is 37. For details, see input and output.
-
Multiple groups of test data are input. Each group of test data occupies one row. There is a space between any two operators and between any two operands. The two input operands may be decimal places. The data ensures that all input operands are positive and smaller than 10, and the number of operands cannot exceed 500.
End sign with EOF as input. Outputs the value of the prefix expression for each group of data. The output result is retained with two decimal places. Sample Input
+ 2 * + 3 4 5+ 5.1 / 3 7
Sample output
37.005.53
Question Analysis:
Using the two stacks to store numbers and operations for computing, I first thought that every time I input two numbers consecutively, the results will be calculated and pushed into the digital stack, in addition, we should ensure that the number of the Back-out stack is in the front, and the number of the first-out stack is in the back, so as to ensure the result ..... Ah, I don't know why Wa is always there. Finally, let's take a look at other people's code. This question can be computed from the back to the back, and we can use operators for computation. Note the conversion from string to number.
AC code:
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Using namespace std; char str [1005]; stack
Dt; int start; void vol () {int I = 0, k = 0; char a [15], B [15]; for (; str [start]! = ''; Start --) {a [k ++] = str [start];} start --; // remove the space a [k] ='' after the number ''; // strrev (); this function cannot use for (I = 0; I
My code:
Int main () {string str; int I, k; double a, B; while (getline (cin, str) {stack
Dt; stack
Ct; I =-1; k = 0; while (I! = Str. size () {++ I; if (str [I] = '') ++ I; if (str [I]> = '0' & str [I] <= '9') {string res; double temp; while (I! = Str. size () & str [I]! = '') Res + = str [I ++]; sscanf (res. c_str (), % lf, & temp); // cout <
1) {a = dt. top (); dt. pop (); B = dt. top (); dt. pop (); char c = ct. top (); ct. pop (); if (c = '+') dt. push (B + a); if (c = '-') dt. push (B-a); if (c = '*') dt. push (B * a); if (c = '/') dt. push (B/a); k = 1 ;}} while (dt. size ()> 1 & ct. size () {// calculate the last a = dt. top (); dt. pop (); B = dt. top (); dt. pop (); char c = ct. top (); ct. pop (); if (c = '+') dt. push (B + a); if (c = '-') dt. push (B-a); if (c = '*') dt. push (B * a); if (c = '/') dt. push (B/a);} int k = 1; if (ct. size () & ct. top () = '-') k =-1; printf (%. 2lf, k * dt. top () ;}return 0 ;}