1#include <iostream>2#include <stack>3#include <string>4#include <vector>5#include <map>6#include <algorithm>7 using namespacestd;8 9map<Const Char,int> priority;//use map to store the precedence of operatorsTen One intCompareCharACharb) { A intCMP =0; - if(b==')'&& a=='(') CMP =0; - Else if(a=='(') CMP =-1; the Else if(Priority[a] < priority[b]) CMP =-1; - Else if(Priority[a] >= priority[b]) cmp =1; - returnCMP; - } + - intCalintAintBCharop) { + intans; A if(op=='+') ans = a +b; at Else if(op=='-') ans = ab; - Else if(op=='*') ans = A *b; - Else if(op=='/') ans =b; - returnans; - } - in intCalculator () { - //depending on the priority level, they can be defined as the following form of precedence to //the precedence of an individual operator is related to the position before and after it needs to be treated with special customs +priority['#'] = -1; -priority[')'] =0; thepriority['+'] =1; *priority['-'] =1; $priority['*'] =2;Panax Notoginsengpriority['/'] =2; -priority['('] =3; thecout<<"Please input valid expression, enter to terminate ..."<<Endl; + CharCH =GetChar (); Astack<Char>op; thestack<int>nums; +Op.push ('#'); -Nums.push (0); $ BOOLFlag =true; $ while(ch!='#'|| Op.top ()! ='#'){ - if(ch<='9'&& ch>='0'){ - intNumber =0; the while(ch>='0'&& ch<='9'){//the number of consecutive occurrences is considered as a whole -Number = number*Ten+ (ch-'0');WuyiCH =GetChar (); the } - //cout<< "Number:" <<number<<endl; Wu //cout<< "OP:" <<ch<<endl; - Nums.push (number); AboutFlag =true; $}Else{//comparing the precedence of the stack top operator and the new output operator - intCMP =Compare (Op.top (), ch); - //cout<< "Compare (" <<op.top () << "," <<ch<< ") =" <<cmp<<endl; - if(cmp==-1){//when the top priority is low, the new operator is pressed to stack A Op.push (CH); +Flag =false; theCH =GetChar (); -}Else if(cmp==0){//that is, the stack top and the new operator are ' (' and ') ' and need to put ' (' Popup $ Op.pop (); theCH =GetChar (); the}Else if(cmp==1){//when the top operator of the stack has high precedence, it is necessary to perform operations the intnum1, num2, Tempans; the CharTempop;//Be sure to note the order of NUM, otherwise it will result in incorrect operation -num2 =nums.top (); in Nums.pop (); theNUM1 =nums.top (); the Nums.pop (); AboutTempop =op.top (); the Op.pop (); theTempans =cal (NUM1, num2, tempop); the //cout<< "Tempans:" <<tempans<<endl; + Nums.push (Tempans); - } the if(ch=='-'&&!flag) Nums.push (0);Bayi the } the } -Cin.Get(); - returnnums.top (); the } the intMain () { the inti =Ten; the while(i--){ -Cout<<calculator () <<Endl; the } the return 0;}
This program has no error-checking function
Input can only contain 0-9,+,-,*,/, (,), #;
#只能出现在表达式尾部表示输入结束
Make sure your expression syntax is correct
Here are some examples
Simple expressions to calculate C + +