學習隨記十一 用順序棧計算逆波蘭表示式

2021-10-22 19:01:53 字數 1860 閱讀 5561

我遇到的主要問題:怎麼儲存表示式以及將表示式中的數字轉化成基本資料型別,我看了許多部落格嘗試過用stringstream的方法,但是每次遇到不知名錯誤除錯求證無果,後找到了c++自帶的型別轉換函式stod,真的很棒(๑•̀ㅂ•́)و✧。

學到的一些知識:字尾表示式的演算法,string與基本資料型別間的轉換,以及用erase函式清空string變數

字尾表示式的演算法:遇到數字存入棧中,遇到操作符號彈出兩個數字計算後存入棧中直到只剩最後結果

**實現(包括我的之前的錯誤**):

注:我是用空格區分數字,且操作符號間不能有空格

#include

#include

#include

const

int stacksize=

100;

typedef

struct stackstack;

using

namespace std;

intisempty

(stack*);

//判棧空

intisfull

(stack*);

//判棧滿

intpush

(stack*

,double);

//進棧

double

pop(stack*);

//退棧

void

input

(string&);

//輸入字尾表示式

double

calculate

(string)

;//計算字尾表示式

intmain

(void

)int

isempty

(stack*p)

intisfull

(stack*p)

intpush

(stack*p,

double x)

else

return1;

//函式正常呼叫

}double

pop(stack*p)

else

}void

input

(string& postfix)

double

calculate

(string postfix)

else

if(postfix[i]

==' '

)else

}else

if(postfix[i]

=='+'

)else

if(postfix[i]

=='-'

)else

if(postfix[i]

=='*'

)else

if(postfix[i]

=='/')}

sum=

pop(

&p);

return sum;

}

輸出示例:

請輸入乙個字尾表示式12

3456

789++

++++

++45

請輸入乙個字尾表示式

12.5

3.64.7

8.432

57.9

++++

+78.132

請輸入乙個字尾表示式

3.546

7.567

4.333*+

36.3338

請輸入乙個字尾表示式

78.567

3.666

8.234

1.577

45.345-++

+/-0.232349

棧之逆波蘭計算器

逆波蘭表示式又叫做字尾。在通常的表示式中,二元運算子總是置於與之相關的兩個運算物件之間,這種表示法也稱為中綴表示。波蘭邏輯學家j.lukasiewicz於1929年提出了另一種表示表示式的方法,按此方法,每一運算子都置於其運算物件之後,故稱為字尾表示。逆波蘭表示式,它的語法規定,表示式必須以逆波蘭表...

單棧實現逆波蘭計算器

標頭檔案 define crt secure no warnings include include include include define error 0 define ok 1 define yes 1 define no 0 typedef int status typedef stru...

C 基礎之用棧計算逆波蘭式

print?include include include typedef struct mystack stack struct mystack int capacity 棧的容量 int top of stack 棧頂下標 int array 存放棧中元素的陣列 棧的建立 stack creat...