C++ 程序打印反向半金字塔

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将学习如何在 C++ 中打印一个反向半金字塔图案。我们将使用两种不同的方法来实现这一目标,一种使用星号(*),另一种使用数字。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/for_loop -.-> lab-96211{{"`C++ 程序打印反向半金字塔`"}} cpp/output -.-> lab-96211{{"`C++ 程序打印反向半金字塔`"}} cpp/user_input -.-> lab-96211{{"`C++ 程序打印反向半金字塔`"}} cpp/files -.-> lab-96211{{"`C++ 程序打印反向半金字塔`"}} cpp/code_formatting -.-> lab-96211{{"`C++ 程序打印反向半金字塔`"}} end

创建 C++ 文件

首先,我们需要在 ~/project 目录下创建一个新的 C++ 文件。我们可以将其命名为 main.cpp。要创建新文件,请打开终端并输入以下命令:

cd ~/project
touch main.cpp

使用星号(*)打印反向半金字塔

在这一步中,我们将编写一个 C++ 程序来使用星号(*)打印反向半金字塔图案。为此,我们需要使用嵌套的 for 循环。外层循环用于遍历行,内层循环用于在每行打印星号。

#include <iostream>
using namespace std;

int main() {
    int rows;

    cout << "Enter number of rows: ";
    cin >> rows;

    for(int i = rows; i >= 1; --i) {
        for(int j = 1; j <= i; ++j) {
            cout << "* ";
        }
        cout << "\n";
    }

    return 0;
}

要运行此程序,我们需要编译并执行它。为此,我们需要在终端中输入以下命令:

g++ main.cpp -o main && ./main

这将编译程序并执行它,输出将显示在终端中。

使用数字打印反向半金字塔

在这一步中,我们将编写一个 C++ 程序来使用数字打印反向半金字塔图案。为此,我们需要在前一个程序的内层循环中将星号替换为数字。

#include <iostream>
using namespace std;

int main() {
    int rows;

    cout << "Enter number of rows: ";
    cin >> rows;

    for(int i = rows; i >= 1; --i) {
        for(int j = 1; j <= i; ++j) {
            cout << j << " ";
        }
        cout << "\n";
    }

    return 0;
}

要运行此程序,我们需要编译并执行它。为此,我们需要在终端中输入以下命令:

g++ main.cpp -o main && ./main

这将编译程序并执行它,输出将显示在终端中。

完整代码

完成上述步骤后,我们的 main.cpp 文件将包含以下代码:

#include <iostream>
using namespace std;

int main() {
    int rows;

    // 使用星号(*)打印反向半金字塔
    cout << "Enter number of rows: ";
    cin >> rows;

    for(int i = rows; i >= 1; --i) {
        for(int j = 1; j <= i; ++j) {
            cout << "* ";
        }
        cout << "\n";
    }

    // 使用数字打印反向半金字塔
    cout << "Enter number of rows: ";
    cin >> rows;

    for(int i = rows; i >= 1; --i) {
        for(int j = 1; j <= i; ++j) {
            cout << j << " ";
        }
        cout << "\n";
    }

    return 0;
}

总结

在本实验中,我们学习了如何使用两种不同的方法在 C++ 中打印反向半金字塔图案——使用星号(*)和使用数字。我们通过嵌套的 for 循环实现了这一图案。此外,我们还学习了如何在终端中编译和运行 C++ 程序。

您可能感兴趣的其他 C++ 教程