四則運算的實現

2021-05-25 05:44:18 字數 1156 閱讀 3694

繼續溫習資料結構...

實現用到了兩個棧:運算元棧與操作符棧。

主要過程是將中序表示式轉換為後續表示式,然後按順序進行運算。

簡單過程:1+8-7(中序)    ---->1 8 7 - +  (後序)--->1 1 +  (運算8-7)---> 2 (運算1+1)

原始碼:#include "stack.h" //利用到了前一篇文章實現的棧

#define size 256

#define psize 512

char postorder[size];

stacks(size);

stackres(size);

int prior(char ch) //自定義優先順序

int comp(int i,int j,char c) //運算

}int compute()

if (postorder[i]>='0'&&postorder[i]<='9'/*&&!res.isfull()*/)

res.push(val);

continue;

} if(res.top>=1)

}return res.pop();

}void change(char *prestr)

postorder[j++]=' ';

} if(prestr[i]==')') //如果為右括號,則進行出棧操作,直到遇到左括號為止

postorder[j++]=s.pop();

postorder[j++]=' ';

}if(s.isempty()&&flag==0)

else if(prestr[i]!=')')

s.push(prestr[i++]);

} }while(!s.isempty()) //遍歷完字串後,將還未出棧的元素全部出棧,記錄在後續表示式的後面

{ if(s.data[s.top]=='(')

{ cout<<"error:do you miss a ')'?"{ cout<<"exception:/nthe size of expression is beyond default value."

<<"/nthe length of a string cannot be larger than "<

實現四則運算

總結最近在看資料結構,遇到第乙個實際棧的應用,記錄 將平時的四則運算表示式又稱為中綴表示式轉化為字尾表示式。遇數字輸出,遇符號進棧,符號優先順序低於棧當前符號則輸出,輸出直到同等優先順序符號。例 9 3 1 2 輸出 棧 9 in 9 in 9 3 9 3 in 9 3 1 9 3 1 in 右括號...

python四則運算程式 四則運算(Python)

四則運算程式 一 資訊 二.題目要求 寫乙個能自動生成小學四則運算題目的程式,然後在此基礎上擴充套件 除了整數以外,還要支援真分數的四則運算,例如 1 6 1 8 7 24 程式要求能處理使用者的輸入,判斷對錯,累積分數 程式支援可以由使用者自行選擇加 減 乘 除運算 三 import random...

java實現四則運算

最近在考慮乙個問題 公司專案可能會使用運算模板來計算相應的值,模板freemarker velocity都是不錯的選擇。那通過模板將計算公式字串組裝出來後,就需要解析字串得到計算結果,以下是我的實現 public class arithmetic public static void main st...