简短的杨辉三角C++实现
注意:需要C++11的支持
一、思想
∵
(kn)=n!k!×(n−k)!
又
(k+1n)=n!(k+1)!×(n−k−1)!
∴
(k+1n)=(kn)×n−kk+1
二、源代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
auto num = 0;
cout << "Please input the num:" << endl;
cin >> num;
for (auto row = 0; row < num; ++row) {
auto temp = 1;
for (auto space = 0; space < num - row; ++space) {
cout << setw(2) << " ";
}
for (auto col = 0; col <= row; ++col) {
cout << " " << setw(4) << temp;
temp = temp * (row - col) / (col + 1);
}
cout << endl;
}
cout << endl;
return 0;
}