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/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/for_loop -.-> lab-96142{{"`C++ 数字半金字塔模式`"}} cpp/output -.-> lab-96142{{"`C++ 数字半金字塔模式`"}} cpp/user_input -.-> lab-96142{{"`C++ 数字半金字塔模式`"}} cpp/files -.-> lab-96142{{"`C++ 数字半金字塔模式`"}} end

在项目目录中创建一个新的 C++ 文件

在终端中使用 cd 命令导航到项目目录,并使用 touch 命令创建一个名为 "half_pyramid_numbers.cpp" 的新 C++ 文件。

cd ~/project
touch half_pyramid_numbers.cpp

输入代码

将以下代码输入到 "half_pyramid_numbers.cpp" 文件中,以打印一个由数字组成的半金字塔结构:

#include <iostream>
using namespace std;

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

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

    //提示用户输入金字塔的行数
    cout << "Enter the number of rows in the pyramid: ";
    cin >> rows;

    //外层循环用于移动到特定行
    for (i = 1; i <= rows; i++)
    {
        //内层循环用于决定特定行中的列数
        for (j = 1; j <= i; j++)
        {
            cout << j << " "; //打印每行中的列号
        }

        cout << endl; //每行打印后移动到下一行
    }

    cout << "\n\n";

    return 0; //结束程序
}

总结

恭喜!你已成功完成了使用 C++ 实现数字半金字塔模式的实验。在本实验中,你学习了如何使用嵌套循环结构打印由数字组成的半金字塔结构。现在,你已经准备好继续学习更复杂的模式和结构了。

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