字首表示式、字尾表示式和中綴表示式的計算(double型)
阿新 • • 發佈:2019-01-01
有關中綴表示式的計算以及中綴表示式與字首表示式、字尾表示式之間的轉換 後續文章會繼續給出
這裡只講字首表示式與字尾表示式計算的實現方法
字首表示式
計算方法:
將得到的字串處理為只含有數字和運算子
將處理後的字串從前到後壓如棧S1中
將棧S1中的元素逐個彈出
若彈出元素判斷為數字 壓入棧S2中
若彈出元素判斷為運算子 從棧S2中彈出兩個元素 與該運算子進行運算 將運算結果重新壓入棧S2中
處理完S1中所有元素後 S2棧頂元素即為計算結果
實現程式碼:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stack> using namespace std; char *Sep=" "; char *p; char str[1005]; double calculate(double a,double b,char c){// 元素的運算順序和字尾表示式相反 if(c=='+') return a+b; if(c=='-') return a-b; if(c=='*') return a*b; if(c=='/') return a/b; } int main (){ while (gets(str)){ stack<char*> S1; stack<double> S2; p=strtok(str,Sep);// 字串處理 以空格為分隔符將字串分隔 壓入棧中 do{ S1.push(p); }while ((p=strtok(NULL,Sep))); while (!S1.empty()){ p=S1.top(); S1.pop(); if (isdigit(p[0]))// 判斷是否為數字 S2.push(atof(p)); else{ double a=S2.top(); S2.pop(); double b=S2.top(); S2.pop(); double temp=calculate(a,b,p[0]); S2.push(temp);// 計算結果重新壓入棧 } } printf ("%g\n",S2.top());// 格式控制 隨便啦 根據題意就好 } return 0; }
字尾表示式
計算方法:
將得到的字串處理為只含有數字和運算子
從前到後判斷分隔後的字元
若判斷為數字壓入棧中
若判斷為運算子 從棧中彈出兩個元素 與該運算子進行運算 將運算結果重新壓入棧中
處理完所有分隔後的字元 棧頂元素即為計算結果
實現程式碼:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stack> using namespace std; char *Sep=" "; char *p; char str[1005]; double calculate(double a,double b,char c){ if(c=='+') return b+a; if(c=='-') return b-a; if(c=='*') return b*a; if(c=='/') return b/a; } int main (){ while (gets(str)){ stack<double> S; p=strtok(str,Sep); do{ if (isdigit(p[0])) S.push(atof(p)); else{ double a=S.top(); S.pop(); double b=S.top(); S.pop(); double temp=calculate(a,b,p[0]); S.push(temp); } }while ((p=strtok(NULL,Sep))); printf ("%g\n",S.top()); } return 0; }
中綴表示式現在寫了