介绍
在本实验中,我们将学习如何使用 C++ 编程语言打印一个由数字组成的反向半金字塔结构。我们将使用嵌套循环结构来迭代并打印该模式。
在本实验中,我们将学习如何使用 C++ 编程语言打印一个由数字组成的反向半金字塔结构。我们将使用嵌套循环结构来迭代并打印该模式。
在终端中,使用以下命令在 ~/project
目录下创建一个名为 main.cpp
的新文件:
touch ~/project/main.cpp
创建文件后,使用文本编辑器打开它。
将以下代码添加到 main.cpp
文件中。
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to print a Reverse Half Pyramid using Numbers ===== \n\n";
//i 用于迭代外层循环,j 用于内层循环
int i, j, rows;
//用于表示每行数字的范围
int last;
cout << "Enter the number of rows in the pyramid: ";
cin >> rows;
cout << "\n\nThe required Reverse Pyramid pattern containing " << rows << " rows is:\n\n";
//外层循环用于移动到特定行
for (i = 1; i <= rows; i++)
{
//显示外层循环维护的行号
cout << "Row ## " << i << " contains numbers from 1 to " << (rows - i + 1) << " : ";
last = rows -i + 1;
//内层循环用于决定特定行中的数字数量
for (j = 1; j<= last; j++)
{
cout << j << " ";
}
cout << endl;
}
cout << "\n\n";
return 0;
}
使用以下命令编译并运行代码:
g++ main.cpp -o main
./main
你将看到以下输出:
Welcome to LabEx :-)
===== Program to print a Reverse Half Pyramid using Numbers =====
Enter the number of rows in the pyramid: 6
The required Reverse Pyramid pattern containing 6 rows is:
Row ## 1 contains numbers from 1 to 6 : 1 2 3 4 5 6
Row ## 2 contains numbers from 1 to 5 : 1 2 3 4 5
Row ## 3 contains numbers from 1 to 4 : 1 2 3 4
Row ## 4 contains numbers from 1 to 3 : 1 2 3
Row ## 5 contains numbers from 1 to 2 : 1 2
Row ## 6 contains numbers from 1 to 1 : 1
在本实验中,我们学习了如何使用 C++ 编程语言中的嵌套循环打印一个由数字组成的反向半金字塔结构。