vae520一生一世
回答數:156 | 被采納數:119
2017-01-18 16:52:35
這是我去年寫的算數表達式的完整算法代碼,你可以借鑒一下:
要用DEV等運行,VC6.0支持不是很好
#include <iostream>#include <vector>#include <stack>#include <string>#include <sstream>using namespace std;string Postfix_Expression;vector <double> StoreData;vector <char>StoreOper;vector <double> StoreQueue;stack < double, vector<double> > Data_Stack(StoreData);stack < char,vector<char>> Oper_Stack(StoreOper);stack < double, vector<double> > Queue_Stack(StoreQueue);inline intPriority( char );void Make_The_Postfix_Stack();void Calculate_The_Postfix_Stack();int main(int argc, char * argv[]){Make_The_Postfix_Stack();Calculate_The_Postfix_Stack();system("pause");return 0;}void Make_The_Postfix_Stack(){size_t Index = 0;string Scrstr;string Buffer;string Check(".0123456789(+-*/)#");char Space;char Char_Temp;double Double_Temp;Oper_Stack.push('#');cout<<"Please enter an expression:"<<endl;check1:getline(cin, Scrstr);if(Scrstr.find_first_not_of(Check,0) != string::npos){ cerr<<"Error input, try again!"<<endl; goto check1;}Scrstr += "#";stringstream PushStream;stringstream TempStream;PushStream.str(Scrstr);while( (PushStream.str().size() - Index) > 0 ){ size_t StringSize; if(isdigit(PushStream.str()[Index])) { PushStream >> Double_Temp; TempStream << Double_Temp; TempStream >> Buffer; StringSize = Buffer.size(); Index += StringSize; Postfix_Expression = Postfix_Expression + " " + Buffer; TempStream.clear(); } else { PushStream >> Char_Temp; switch(Char_Temp) { case '(': Oper_Stack.push(Char_Temp); break; case ')': case '#': do{ Char_Temp = Oper_Stack.top(); Oper_Stack.pop(); if(Char_Temp != '(' && Char_Temp != '#') Postfix_Expression = Postfix_Expression + " " + Char_Temp; }while(Char_Temp!='(' && !Oper_Stack.empty()); break; case '+': case '-': case '*': case '/': while(Priority(Char_Temp) <= Priority(Oper_Stack.top())) { Postfix_Expression = Postfix_Expression + " " + Oper_Stack.top(); Oper_Stack.pop(); } Oper_Stack.push(Char_Temp); break; } Index ++; } }}int Priority( char ch ){int priority;switch( ch ){ case '+' : priority = 1; break; case '-' : priority = 1; break; case '*' : priority = 2; break; case '/' : priority = 2; break; default : priority = 0; break;}return priority;}void Calculate_The_Postfix_Stack(){size_t size = 0;string Buffer;stringstream sstr;stringstream temp;double Value_Buffer;double x,y;char Oper_Buffer;sstr.str(Postfix_Expression);while( (sstr.str().size() - size) > 0 ){ if(isdigit(sstr.str()[size])||isdigit(sstr.str()[size+1])) { sstr >> Value_Buffer; temp << Value_Buffer; temp >> Buffer; size += (Buffer.size() + 1); temp.clear(); Queue_Stack.push(Value_Buffer); } else { sstr >> Oper_Buffer; y = Queue_Stack.top(); Queue_Stack.pop(); x = Queue_Stack.top(); Queue_Stack.pop(); switch(Oper_Buffer) { case '+': Queue_Stack.push( x+y ); break; case '-': Queue_Stack.push( x-y ); break; case '*': Queue_Stack.push( x*y ); break; case '/': Queue_Stack.push( x/y ); break; } size += 2; }}cout<<"Result = "<<Queue_Stack.top()<<endl;}複製代碼