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-96220{{"`C++ 使用星号打印反向半金字塔图案`"}} cpp/output -.-> lab-96220{{"`C++ 使用星号打印反向半金字塔图案`"}} cpp/user_input -.-> lab-96220{{"`C++ 使用星号打印反向半金字塔图案`"}} cpp/files -.-> lab-96220{{"`C++ 使用星号打印反向半金字塔图案`"}} cpp/code_formatting -.-> lab-96220{{"`C++ 使用星号打印反向半金字塔图案`"}} end

设置项目

打开终端,在 ~/project 目录下创建一个名为 pyramid.cpp 的 C++ 源文件:

cd ~/project
touch pyramid.cpp

使用文本编辑器打开该文件。

编写代码

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

//Cpp Reverse Half Pyramid Pattern Using Asterix
//Nested Loop Structure
#include <iostream>
using namespace std;

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

    //i to iterate the outer loop and j for the inner loop
    int i, j, rows;

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

    //outer loop is used to move to a particular row
    for (i = 1; i <= rows; i++)
    {
        //to display that the outer loop maintains the row number
        cout << "Row ## " << i << " contains " << (rows - i + 1) << " stars :  ";

        //inner loop is used to decide the number of * in a particular row
        for (j = rows; j >= i; j--)
        {
            cout << "* ";
        }

        cout << endl;
    }

    cout << "\n\n";

    return 0;
}

该程序接收用户输入的行数 rows,并使用 * 显示用户输入行数的反向半金字塔图案。

保存并编译代码

保存对 pyramid.cpp 文件的更改并退出文本编辑器。在终端中使用以下命令编译代码:

g++ pyramid.cpp -o pyramid

运行代码

在终端中输入以下命令以执行编译后的程序:

./pyramid

输入金字塔的行数,程序将输出包含指定行数的反向半金字塔图案。

总结

恭喜!你已经成功完成了使用 C++ 打印星号反向半金字塔图案的实验。

嵌套循环结构对于创建此类图案非常有用。理解循环的工作原理以及如何通过它们进行迭代,对于构建更复杂的图案非常重要。

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