1. 程式人生 > >當代碼比較長,特別是有多重嵌套時,應當在一些段落的結束處加註釋

當代碼比較長,特別是有多重嵌套時,應當在一些段落的結束處加註釋

getch code return input under init iostream 結束 get

 1 #include <iostream>
 2 const int MAX=5;
 3 using namespace std;
 4 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 5      //假定棧中最多保存5個數據
 6 
 7 //定義名為stack的類,其具有棧功能
 8 class  stack {
 9     //數據成員
10     float  num[MAX];  //存放棧數據的數組
11     int  top;          //
指示棧頂位置的變量 12 public: 13 //成員函數 14 void init(void) { top=0; } //初始化函數 15 void push(float x) //入棧函數 16 { 17 if (top==MAX){ 18 cout<<"Stack is full !"<<endl; 19 return; 20 }; 21 num[top]=x; 22 top++; 23 } 24 float
pop(void) //出棧函數 25 { 26 top--; 27 if (top<0){ 28 cout<<"Stack is underflow !"<<endl; 29 return 0; 30 }; 31 return num[top]; 32 } 33 34 }; 35 int main(int argc, char** argv) { 36 //聲明變量和對象 37 int i; 38 float x;
39 stack a,b; //聲明(創建)棧對象 40 41 //以下對棧對象初始化 42 a.init(); 43 b.init(); 44 45 //以下利用循環和push()成員函數將2,4,6,8,10依次入a棧對象 46 for (i=1; i<=MAX; i++) 47 a.push(2*i); 48 49 //以下利用循環和pop()成員函數依次彈出a棧中的數據並顯示 50 for (i=1; i<=MAX; i++) 51 cout<<a.pop()<<" "; 52 cout<<endl; 53 54 //以下利用循環和push()成員函數將鍵盤輸入的數據依次入b棧 55 cout<<"Please input five numbers."<<endl; 56 for (i=1; i<=MAX; i++) { 57 cin>>x; 58 b.push(x); 59 } 60 61 //以下利用循環和pop()成員函數依次彈出b棧中的數據並顯示 62 for (i=1; i<=MAX; i++) 63 cout<<b.pop()<<" "; 64 return 0; 65 }

,便於閱讀。

當代碼比較長,特別是有多重嵌套時,應當在一些段落的結束處加註釋