巴斯卡三角形

void main(void){
    int M[50][100] = {0};
    int r,c;
    cout << "請輸入巴斯卡三角形的列數:"; cin >> r;
    c = 2*r - 1;

    M[0][c/2] = 1;

    for (int rl = 1; rl < r; rl++) {
        for (int cl = 0; cl < c; cl++) {
            M[rl][cl] = M[(rl-1+r)%r][(cl-1+c)%c] + M[(rl-1+r)%r][(cl+1)%c]; //元素的值為其左上角元素與右上角元素的和
        }
    }

    //底下輸出陣列
    for (int rl = 0; rl < r; rl++) {
        for (int cl = 0; cl < c; cl++) {    
            if (M[rl][cl] == 0) cout << " " << " "; 
            else cout << M[rl][cl] << " ";
        }
        cout << endl;
    }

    //以上輸出在超過2位數以上的時候,就無法對齊,請使用setw來固定輸出寬度(自己完成)
    system("pause");
}

另一種解法,三角形從陣列位置1,1來填…

#include <iostream>
#include <iomanip>      // std::setw


using namespace std;
void main(void){
    int M[50][100] = {0};
    int r,c;
    cout << "請輸入巴斯卡三角形的列數:"; cin >> r;
    c = 2*r - 1;
    M[1][c/2+1] = 1;

    for (int i = 2; i <= r; i++) {
        for (int j = 1; j <= c ; j++){
            M[i][j] = M[i-1][j-1] + M[i-1][j+1];
        }
    }

    for (int i = 1; i <= r; i++) {
        for (int j = 1; j <= c ; j++){
            if (M[i][j] == 0) cout << setw(4) << " ";
            else cout << M[i][j] << setw(4) << " ";;
        }
        cout << endl;
    }

 system("PAUSE");
}

results matching ""

    No results matching ""