使用 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/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/for_loop -.-> lab-96244{{"`使用 C++ 打印完整金字塔的程序`"}} cpp/output -.-> lab-96244{{"`使用 C++ 打印完整金字塔的程序`"}} cpp/user_input -.-> lab-96244{{"`使用 C++ 打印完整金字塔的程序`"}} cpp/code_formatting -.-> lab-96244{{"`使用 C++ 打印完整金字塔的程序`"}} end

包含必要的头文件

在这一步中,你需要包含必要的头文件。

#include<iostream>
using namespace std;

创建主函数

在这一步中,你将创建主函数,这是程序的入口点。

int main()
{
    int space, rows;

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

    for(int i = 1, k = 0; i <= rows; ++i, k = 0)
    {
        for(space = 1; space <= rows-i; ++space)
        {
            cout <<"  ";
        }

        while(k != 2*i-1)
        {
            cout << "* ";
            ++k;
        }
        cout << endl;
    }

    return 0;
}

测试程序

要测试程序,请在终端中运行以下命令。

g++ main.cpp -o main && ./main

你将看到以下输出:

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

完整代码

以下是 main.cpp 的完整代码。

#include<iostream>
using namespace std;

int main()
{
    int space, rows;

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

    for(int i = 1, k = 0; i <= rows; ++i, k = 0)
    {
        for(space = 1; space <= rows-i; ++space)
        {
            cout <<"  ";
        }

        while(k != 2*i-1)
        {
            cout << "* ";
            ++k;
        }
        cout << endl;
    }

    return 0;
}

总结

在本实验中,你学习了如何编写一个 C++ 程序,通过提示用户输入要打印的行数,并使用 * 打印一个完整的金字塔。现在你可以练习使用这个程序,为自己的项目创建类似的图案。

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