c++

C++如何优雅地打印杨辉三角形

小樊
119
2024-07-05 19:11:28
栏目: 编程语言

下面是一个优雅地打印杨辉三角形的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;
}

运行这段代码,用户输入所需的行数,程序将打印出相应行数的杨辉三角形。

0
看了该问题的人还看了