阅读量:140
下面是一个用C++编写的杨辉三角形代码示例:
#include
using namespace std;
int main() {
int numRows;
cout << "请输入要打印的杨辉三角形的行数:";
cin >> numRows;
int triangle[numRows][numRows];
// 初始化杨辉三角形
for (int i = 0; i < numRows class="hljs-number">0] = 1;
triangle[i][i] = 1;
}
for (int i = 2; i < numRows class="hljs-keyword">for (int j = 1; j < i xss=removed class="hljs-number">-1][j-1] + triangle[i-1][j];
}
}
// 打印杨辉三角形
for (int i = 0; i < numRows class="hljs-keyword">for (int j = 0; j <= i; j++) {
cout << triangle class="hljs-string">" ";
}
cout << endl class="hljs-keyword">return 0;
}
你可以运行这个代码,输入想要打印的杨辉三角形的行数,然后代码会输出对应的杨辉三角形。