C++ 星号半金字塔图案程序

C++C++Beginner
立即练习

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

介绍

在本实验中,你将学习如何使用 C++ 编程语言创建一个由星号(*)组成的半金字塔图案。本实验将教你如何使用迭代实现各种嵌套循环结构。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp/BasicsGroup -.-> cpp/operators("`Operators`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") subgraph Lab Skills cpp/operators -.-> lab-96143{{"`C++ 星号半金字塔图案程序`"}} cpp/for_loop -.-> lab-96143{{"`C++ 星号半金字塔图案程序`"}} cpp/output -.-> lab-96143{{"`C++ 星号半金字塔图案程序`"}} cpp/user_input -.-> lab-96143{{"`C++ 星号半金字塔图案程序`"}} cpp/files -.-> lab-96143{{"`C++ 星号半金字塔图案程序`"}} end

~/project 目录中创建一个新文件

首先,在终端中使用 touch 命令在 ~/project 目录中创建一个名为 half_pyramid_star.cpp 的新文件:

touch ~/project/half_pyramid_star.cpp

输入代码

现在,在文本编辑器或 IDE 中打开 half_pyramid_star.cpp 文件,并将以下代码复制到其中:

#include <iostream>
using namespace std;

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

    int i, j, rows;
    cout << "Enter the number of rows in the pyramid: ";
    cin >> rows;

    //outer loop moves to a specific row
    for (i = 1; i <= rows; i++)
    {
        //inner loop determines the amount of "*" printed in the row
        for (j = 1; j <= i; j++)
        {
            cout << "* ";
        }

        cout << endl;
    }

    cout << "\n\n";
    return 0;
}

上述代码会提示用户输入要打印的半金字塔图案的行数,并使用两个嵌套循环在每一行打印“*”。

编译并运行代码

在终端窗口中输入以下命令以编译 half_pyramid_star.cpp 代码:

g++ ~/project/half_pyramid_star.cpp -o ~/project/half_pyramid_star && ~/project/half_pyramid_star

上述命令将编译代码,生成一个名为 half_pyramid_star 的可执行文件,并运行该程序。

总结

在本实验中,你学习了如何使用 C++ 编程语言创建一个由星号(*)组成的半金字塔图案。通过利用嵌套循环并理解其作用范围,你成功完成了实验。本实验是理解嵌套循环结构和迭代的基础步骤,这将有助于解决问题或创建复杂的形状。

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