資料結構|用棧實現十進位制轉換成二進位制(實驗3.5)
阿新 • • 發佈:2019-01-29
一、實驗目的
1、熟練掌棧的結構特點,掌握棧的順序儲存結構和實現。
2、學會使用棧解決實際問題。
二、實驗內容
1、自己確定結點的具體資料型別和問題規模,建立一個順序棧,實現棧的壓棧和出棧操作。
三、實驗步驟
1、依據實驗內容分別說明實驗程式中用到的資料型別的定義;
class SeqStack { private: int data[Size]; //資料儲存陣列 int top; public: SeqStack (){top=-1;} ~SeqStack (){} void Push(int x); //入棧操作 void Pop(); //出棧操作 };
2、相關操作的演算法表達;
2.1、建構函式,初始化一個空棧
2.2、入棧操作函式:①.判斷是否棧滿,若是則丟擲上溢錯誤,否則
②.進行十進位制向二進位制的轉換
2.3、出棧操作函式:①判斷是否棧空,若是則丟擲下溢錯誤,否則
②先返回棧頂指標 top 指向的位置的值,再把棧頂指標 top 往下移一位,輸出數值
3、完整程式;
由於結點元素型別不確定,因此採用C++模板機制。
原始碼如下:
#include<iostream> using namespace std; const int Size = 50; class SeqStack { private: int data[Size]; //資料儲存陣列 int top; public: SeqStack (){top=-1;} ~SeqStack (){} void Push(int x); //入棧操作 void Pop(); //出棧操作 }; void SeqStack ::Push(int x) { top=-1; int y; int m=2; if(top==Size-1) throw "上溢"; while(x!=0) { y=x%m; data[++top]=y; x=x/m; }; } void SeqStack ::Pop() { if (top == -1) throw "下溢"; while(top!=-1) { int x=data[top--]; cout<<x; } } void main() { int i=1; int number; SeqStack a; do{ cout<<"請輸入一個十進位制整數!"<<endl; cin>>number; a.Push(number); a.Pop(); cout<<endl; cout<<"若需要繼續轉換,請輸入1;否則請輸入0!"<<endl; cin>>i; }while(i==1); }
4、總結、執行結果和分析。
①總結
在程式內輸入物件,將物件入棧。
通過呼叫函式,實現入棧、出棧、進位制轉換等基本功能。
②執行結果如下:
5、總體收穫和不足,疑問等。
本次試驗較為簡單,因為實驗內容較少,且對書本知識掌握得有點熟悉。但本次試驗還是發現了自己的不足之處。經過改進、詢問同學,成功完成了實驗。收穫頗豐。總的來說,我對理論知識有了更充分的理解,也能較大程度明白執行原理。