C++ 半金字塔图案打印

C++Beginner
立即练习

介绍

在本实验中,我们将学习如何使用星号(*)和字母的交替来打印一个半金字塔图案。我们将使用 C++ 编程语言来编写这个程序的代码。本实验适合想要练习 C++ 编程技能的初学者。

创建一个新的 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++ 中的星号和字母交替打印半金字塔图案。我们使用了循环和条件语句等基本编程概念来生成图案。随后,我们编译并运行了程序以测试代码。