// exam1.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <stack> using namespace std; int priority(char op) { switch(op) { case '(': return 1; case '+': case '-': return 2; case '*': case '/': return 3; case ')': return 4; case '#': return 5; } } bool cmp_lg(char op1,char op2) { int proi1=priority(op1); int proi2=priority(op2); if(proi1>=proi2) { return true; } else { return false; } } int cal_func(char op,int num1,int num2) { switch(op) { case '+': return num1+num2; case '-': return num1-num2; case '*': return num1*num2; case '/': return num1/num2; default: return num1+num2; } } void cal(void) { cout<<"Please enter the formula whose end is '#'..."<<endl; char ch; stack<int> num; stack<char> op; while(1) { cin>>ch; if(ch=='#') { break; } if(ch>='0' && ch<='9') { num.push(ch-'0'); } else { if(op.empty()) { op.push(ch); } else { char op1,op2; op1=op.top(); op2=ch; if(ch=='(') { op.push(ch); } else if(cmp_lg(op1,op2)) { int result,num1,num2; num1=num.top(); num.pop(); num2=num.top(); num.pop(); result=cal_func(op1,num1,num2); num.push(result); op.pop(); op.push(op2); } else { if(ch==')') { int result; int num1,num2; char op0; num1=num.top(); num.pop(); num2=num.top(); num.pop(); op0=op.top(); op.pop(); op.pop(); result=cal_func(op0,num1,num2); num.push(result); } else { op.push(ch); } } } } } while(!num.empty() && !op.empty()) { int result; int num1,num2; char op0; num1=num.top(); num.pop(); num2=num.top(); num.pop(); op0=op.top(); op.pop(); result=cal_func(op0,num1,num2); num.push(result); } cout<<"The result is "<<num.top()<<"."<<endl; } int main(void) { cal(); system("pause"); return 0; }
原文:http://blog.csdn.net/cjc211322/article/details/38356065