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-96222{{"`C++ 使用数字打印反向半金字塔模式`"}} cpp/output -.-> lab-96222{{"`C++ 使用数字打印反向半金字塔模式`"}} cpp/user_input -.-> lab-96222{{"`C++ 使用数字打印反向半金字塔模式`"}} cpp/files -.-> lab-96222{{"`C++ 使用数字打印反向半金字塔模式`"}} cpp/code_formatting -.-> lab-96222{{"`C++ 使用数字打印反向半金字塔模式`"}} end

创建并打开文件

在终端中,使用以下命令在 ~/project 目录下创建一个名为 main.cpp 的新文件:

touch ~/project/main.cpp

创建文件后,使用文本编辑器打开它。

编写初始代码

将以下代码添加到 main.cpp 文件中。

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " =====  Program to print a Reverse Half Pyramid using Numbers ===== \n\n";

    //i 用于迭代外层循环,j 用于内层循环
    int i, j, rows;

    //用于表示每行数字的范围
    int last;

    cout << "Enter the number of rows in the pyramid: ";
    cin >> rows;
    cout << "\n\nThe required Reverse Pyramid pattern containing " << rows << " rows is:\n\n";

    //外层循环用于移动到特定行
    for (i = 1; i <= rows; i++)
    {
        //显示外层循环维护的行号
        cout << "Row ## " << i << " contains numbers from 1 to " << (rows - i + 1) << " :  ";

        last  = rows -i + 1;
        //内层循环用于决定特定行中的数字数量
        for (j = 1; j<= last; j++)
        {
            cout << j << " ";
        }

        cout << endl;
    }

    cout << "\n\n";

    return 0;
}

编译并运行代码

使用以下命令编译并运行代码:

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

你将看到以下输出:

Welcome to LabEx :-)


 =====  Program to print a Reverse Half Pyramid using Numbers =====

Enter the number of rows in the pyramid: 6


The required Reverse Pyramid pattern containing 6 rows is:

Row ## 1 contains numbers from 1 to 6 :  1 2 3 4 5 6
Row ## 2 contains numbers from 1 to 5 :  1 2 3 4 5
Row ## 3 contains numbers from 1 to 4 :  1 2 3 4
Row ## 4 contains numbers from 1 to 3 :  1 2 3
Row ## 5 contains numbers from 1 to 2 :  1 2
Row ## 6 contains numbers from 1 to 1 :  1

总结

在本实验中,我们学习了如何使用 C++ 编程语言中的嵌套循环打印一个由数字组成的反向半金字塔结构。

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