C++ 中的翻转半金字塔图案

C++C++Beginner
立即练习

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

介绍

在本实验中,我们将使用 C++ 编写一个程序,用 * 符号打印一个半金字塔的翻转图案。我们将以每行的星号数量从最大值开始,然后在每一连续行中递减的方式打印该图案。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp(("C++")) -.-> cpp/ControlFlowGroup(["Control Flow"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp(("C++")) -.-> cpp/StandardLibraryGroup(["Standard Library"]) cpp/BasicsGroup -.-> cpp/variables("Variables") cpp/BasicsGroup -.-> cpp/data_types("Data Types") 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/StandardLibraryGroup -.-> cpp/standard_containers("Standard Containers") cpp/SyntaxandStyleGroup -.-> cpp/comments("Comments") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/variables -.-> lab-96206{{"C++ 中的翻转半金字塔图案"}} cpp/data_types -.-> lab-96206{{"C++ 中的翻转半金字塔图案"}} cpp/for_loop -.-> lab-96206{{"C++ 中的翻转半金字塔图案"}} cpp/output -.-> lab-96206{{"C++ 中的翻转半金字塔图案"}} cpp/user_input -.-> lab-96206{{"C++ 中的翻转半金字塔图案"}} cpp/files -.-> lab-96206{{"C++ 中的翻转半金字塔图案"}} cpp/standard_containers -.-> lab-96206{{"C++ 中的翻转半金字塔图案"}} cpp/comments -.-> lab-96206{{"C++ 中的翻转半金字塔图案"}} cpp/code_formatting -.-> lab-96206{{"C++ 中的翻转半金字塔图案"}} end

创建新文件

首先,在终端中运行以下命令,在 ~/project 目录下创建一个名为 flip_pattern_half_pyramid.cpp 的新文件:

touch ~/project/flip_pattern_half_pyramid.cpp

包含头文件

我们将从在代码中包含必要的头文件开始。

#include <iostream>

iostream 头文件包含了 C++ 中的标准输入输出函数。

创建 main() 函数

这是我们程序的主函数。

int main()
{
   // 代码将写在这里
   return 0;
}

声明变量

我们将声明 rows 变量来存储行数,该值稍后由用户输入。

int rows;

获取用户输入

我们将要求用户输入他们想要的图案行数。

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

创建循环

在这里,我们将使用两个嵌套循环来打印半金字塔的翻转图案。

for(int i = rows; i >= 1; --i)
{
    for(int j = 1; j <= i; ++j)
    {
        std::cout << "* ";
    }
    std::cout << std::endl;
}

组合代码

将上述所有代码组合起来,生成以下代码:

#include<iostream>

int main()
{
    int rows;

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

    for(int i = rows; i >= 1; --i)
    {
        for(int j = 1; j <= i; ++j)
        {
            std::cout << "* ";
        }
        std::cout << std::endl;
    }

    return 0;
}

运行代码

要运行上述代码,请按照以下步骤操作:

  1. 打开终端。

  2. 导航到 flip_pattern_half_pyramid.cpp 文件所在的目录。

  3. 使用以下命令编译代码:

    g++ flip_pattern_half_pyramid.cpp -o flip_pattern_half_pyramid
  4. 使用以下命令运行代码:

    ./flip_pattern_half_pyramid
  5. 当程序提示时,输入你想要的图案行数。

输出

运行程序后,你将在终端屏幕上看到以下输出。

Enter the number of rows: 5
* * * * *
* * * *
* * *
* *
*

总结

在本实验中,我们成功创建了一个 C++ 程序,使用 * 符号打印出半金字塔的翻转图案。我们通过使用嵌套循环和基本语法构建了这个程序。