下面是一個優雅地打印楊輝三角形的C++代碼示例:
#include <iostream>
#include <vector>
void printPascalTriangle(int numRows) {
std::vector<std::vector<int>> triangle(numRows);
for (int i = 0; i < numRows; i++) {
triangle[i].resize(i + 1);
triangle[i][0] = triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
for (int i = 0; i < numRows; i++) {
for (int j = 0; j <= i; j++) {
std::cout << triangle[i][j] << " ";
}
std::cout << std::endl;
}
}
int main() {
int numRows;
std::cout << "Enter the number of rows for Pascal's Triangle: ";
std::cin >> numRows;
printPascalTriangle(numRows);
return 0;
}
運行這段代碼,用戶輸入所需的行數,程序將打印出相應行數的楊輝三角形。