C++ 半金字塔图案打印

C++C++Beginner
立即练习

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

介绍

在本实验中,我们将学习如何使用星号(*)和字母的交替来打印一个半金字塔图案。我们将使用 C++ 编程语言来编写这个程序的代码。本实验适合想要练习 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/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/if_else("`If...Else`") 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/conditions -.-> lab-96207{{"`C++ 半金字塔图案打印`"}} cpp/if_else -.-> lab-96207{{"`C++ 半金字塔图案打印`"}} cpp/for_loop -.-> lab-96207{{"`C++ 半金字塔图案打印`"}} cpp/output -.-> lab-96207{{"`C++ 半金字塔图案打印`"}} cpp/user_input -.-> lab-96207{{"`C++ 半金字塔图案打印`"}} cpp/files -.-> lab-96207{{"`C++ 半金字塔图案打印`"}} cpp/code_formatting -.-> lab-96207{{"`C++ 半金字塔图案打印`"}} end

创建一个新的 C++ 文件

~/project 目录下创建一个名为 main.cpp 的 C++ 文件。我们将在此文件中编写程序的代码。

touch ~/project/main.cpp

编写代码

将以下代码复制并粘贴到 main.cpp 文件中。此代码将使用星号和字母的交替打印半金字塔图案。

#include <iostream>
using namespace std;

int main()
{
    int i, j, n;
    cout << "Enter the number of rows: ";
    cin >> n;

    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= i; j++)
        {
            if(j % 2 == 0)
                cout << "A";
            else
                cout << "*";
        }
        cout << "\n";
    }
    return 0;
}

编译并运行代码

打开终端,使用 cd project 命令导航到 ~/project 目录。然后,使用以下命令编译 main.cpp 文件:

g++ main.cpp -o main

此命令将生成一个名为 main 的可执行文件。要运行程序,请使用以下命令:

./main

程序会要求你输入图案的行数。输入所需的数字并按 Enter 键。程序将使用星号和字母的交替打印出半金字塔图案。

完整代码

以下是 main.cpp 文件的完整代码:

#include <iostream>
using namespace std;

int main()
{
    int i, j, n;
    cout << "Enter the number of rows: ";
    cin >> n;

    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= i; j++)
        {
            if(j % 2 == 0)
                cout << "A";
            else
                cout << "*";
        }
        cout << "\n";
    }
    return 0;
}

总结

在本实验中,我们学习了如何使用 C++ 中的星号和字母交替打印半金字塔图案。我们使用了循环和条件语句等基本编程概念来生成图案。随后,我们编译并运行了程序以测试代码。

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