Calcular

#include<iostream> using namespace std; int st[100000]; int top = 0; void Init() { top =0; } bool is_Empty(){ if(top==0) return true; else return false; } void push(int x) { st[top++]=x; } int pop() { top --; return st[top]; } int peak() { return st[top-1]; } int Pre(char x) { if (x == '(') return 0; else if (x == '+' || x == '-') return 1 ; else if (x == '*' || x == '/' || x == '%') return 2; return 3; } void Hauto(char a[], char b[]) { int j = 0; char x, tk; Init(); for(int i = 0; a[i] != '\0'; i++) { tk = a[i]; if(tk >='0' && tk <='9') { b[j++]=tk; } else if(tk=='(') push(tk); else if(tk==')') { while((x= pop()) != '(') { b[j++]=x; } } else { while(Pre(tk) <= Pre(peak()) && !is_Empty() ) { x = pop(); b[j++]= x; } push(tk); } } while(top>0) { x=pop(); b[j++]=x; } b[j]='\0'; } int Tinhgt(char b[]) { int op1, op2, res=0; for(int i = 0; b[i] != '\0'; i++) { if(b[i] >='0' && b[i]<='9') { int num = b[i]-'0'; push(num); } else { op1 = pop(); op2=pop(); switch(b[i]) { case '+': res = op2+op1; break; case '*': res = op2*op1; break; default: cout << "\nInvalid Operator"; break; } push(res); } } res = pop(); return res; } int main() { char a[100000], b[100000]; int n; float op1, op2, res=0; freopen("input.txt","r",stdin); for(int tc =1; tc<=10; tc++) { cin >> n; cin>>a; Hauto(a,b); cout <<"#"<<tc<<" "<<Tinhgt(b)<<endl; } return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.