一、計算器實現的思路
在計算器的實現中,需要將用戶輸入的算式轉換成計算機可以識別和處理的形式,然後進行計算並輸出結果。
第一步是將用戶輸入的中綴表達式轉換成後綴表達式,這樣方便計算機進行計算。在轉換中,需要注意運算符的優先順序。
第二步是將轉換後的後綴表達式利用棧進行計算,遇到操作數則壓入棧中,遇到運算符則出棧兩個操作數進行運算,並將運算結果壓入棧中。
第三步是將棧中最後一個元素即為計算結果,將其輸出給用戶。
二、中綴轉後綴的實現
中綴表達式轉後綴表達式可以使用棧來實現,在將運算符壓入棧中前需要彈出優先順序比它高或相等的運算符。
vector infix2postfix(vector infix){ stack s; vector postfix; map priority; priority["+"] = 1; priority["-"] = 1; priority["*"] = 2; priority["/"] = 2; priority["("] = 0; for(int i=0;i=priority[token]){ postfix.push_back(s.top()); s.pop(); } s.push(token); } } while(!s.empty()){ postfix.push_back(s.top()); s.pop(); } return postfix; }
三、後綴表達式的計算實現
後綴表達式的計算可以使用棧來實現,在遇到操作數時將其壓入棧中,在遇到運算符時彈出棧頂的兩個元素進行計算,將結果再次壓入棧中。
int eval_postfix(vector postfix){ stack s; for(int i=0;i<postfix.size();i++){ string token = postfix[i]; if(isdigit(token[0])){ s.push(stoi(token)); } else{ int b = s.top(); s.pop(); int a = s.top(); s.pop(); if(token=="+"){ s.push(a+b); } else if(token=="-"){ s.push(a-b); } else if(token=="*"){ s.push(a*b); } else{ s.push(a/b); } } } return s.top(); }
四、完整代碼示例
#include #include #include
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/297149.html