Algorithm training prefix expression time limit: 1.0s memory Limit: 512.0MB problem description Write a program, enter a prefix expression as a string, and then calculate its value. The input format is: "Operator Object 1 Object 2", where the operator is "+" (addition), "-" (subtraction), "*" (multiplication), or "/" (division), and the operands are integers of not more than 10, separated by a space. Requirements: for addition, subtraction, multiplication, in addition to these four kinds of operations, respectively, design the corresponding function to achieve.
Input format: Enter only one row, which is a prefix expression string.
Output format: Outputs the corresponding calculation results (in the case of division, the C-language "/" operator is used directly, and the result is an integer).
Input and Output Sample sample input + 5 2 sample output 7 ps:http://lx.lanqiao.org/problem.page?gpid=t225
who can tell me, what's wrong ... No love!
#include <stdio.h>#include<stack>#include<string.h>using namespaceStd;stack<int>s;voidFunCharop) { //printf ("%c\n", op); intx, y; if(S.empty ())return ; X=S.top (); S.pop (); //printf ("%d\n", x); if(S.empty ())return ; Y=S.top (); S.pop (); //printf ("x=%d,y=%d\n", X, y); Switch(OP) { Case'+': x+=y; Break; Case'-': x-=y; Break; Case'*': x*=y; Break; Case'/': x/=y; Break; } s.push (x);}Charch[10005];intMain () {intLen,x,y; Gets (CH);//printf ("%s\n", ch);len=strlen (CH);//printf ("%d\n", Len); for(inti=len-1; i>=0; i--) { if(ch[i]==' ')Continue; //printf ("%c", Ch[i]); if(ch[i]>='0'&&ch[i]<='9') { intxx=ch[i]-'0'; S.push (XX); } Else if(ch[i]=='+') Fun (Ch[i]); Else if(ch[i]=='-') Fun (Ch[i]); Else if(ch[i]=='*') Fun (Ch[i]); Else if(ch[i]=='/') Fun (Ch[i]); } if(!s.empty ()) printf ("%d\n", S.top ()); S.pop (); return 0;}
And then search the Internet, I have no words ....
#include <iostream>#include<cstdio>using namespacestd;intMain () {CharC; intn,m; scanf ("%c",&c); scanf ("%d%d",&n,&m); if(c=='+') printf ("%d\n", n+m); if(c=='-') printf ("%d\n", N-m); if(c=='*') printf ("%d\n"Nm); if(c=='/') printf ("%d\n", n/m); return 0;}View Code
This code can actually be too .....
The great Gods come to rescue me. Help me look at the code;
Algorithm training prefix expression (Blue Bridge cup)