程式基本演算法習題解析 編寫程式碼實現楊輝三角
阿新 • • 發佈:2018-12-18
先附上書上的程式碼(書上用c寫的,這裡轉換成了c++,但是思路沒變):
#include "stdafx.h" #include<iostream> using namespace std; int main() { int a[11][20],i,j; for(i=0;i<11;i++) for(j=0;j<20;j++) a[i][j] = 0; for(i=0;i<10;i++) { for(j=0;j<=i;j++) { if(j<1) a[i][j] = 1; else if(i==0) break; else a[i][j] = a[i-1][j-1]+a[i-1][j]; } } for(i=0;i<10;i++) { for(j=0;j<=i;j++) cout << a[i][j]; cout << endl; } system("pause"); return 0; }
執行結果如下:
但是我認為書上這個程式寫得不完善,首先,不能自定義行數,其次,輸出值之間沒有間隔且不是以美觀的三角形式進行輸出。
針對以上問題,我對程式做了改進,如下:
// Chapter1_7.cpp : Defines the entry point for the application. // 編寫程式碼實現楊輝三角 #include "stdafx.h" #include<iostream> using namespace std; int main() { int layer,row,colume; cout << "input the number of layers: " ; cin >> layer; row = layer; colume = 2*layer-1; //申請空間 int **a = new int *[row]; int i,j; for(i=0;i<row;i++) { a[i] = new int[colume]; } //賦初值 for(i=0;i<row;i++) for(j=0;j<colume;j++) a[i][j] = 0; //使用空間 for(i=0;i<row;i++) { for(j=0;j<colume;j++) { a[i][row-i-1] = 1; a[i][row+i-1] = 1; if(i<(row-1) && j<=(row+i-1) && a[i][j]!=NULL && a[i][j+2]!=NULL) { a[i+1][j+1] = a[i][j]+a[i][j+2]; } } } for(i=0;i<row;i++) { for(j=0;j<colume;j++) { if(a[i][j] == 0) cout << ' '; //將0值用空格代替 else cout << a[i][j]; } cout << endl; } //釋放空間 for(i = 0;i<row;i++) { delete a[i]; a[i] = NULL; } delete [row]a; a = NULL; system("pause"); return 0; }
這裡用到了二維陣列的動態建立,需要注意的是,陣列用完之後需記得將其釋放。另外就是輸出,如果直接輸出陣列a[i][j],那麼沒有數字的地方會以0填充,看起來並不美觀,但是將陣列中的0值賦為空格符號,那又涉及到int型和char型別的轉換,並不方便,因此考慮不輸出0值,在0值處輸出一個空格,便解決了該問題。
執行結果如下:
可見,改進後的程式更靈活,輸出更美觀。