介绍
在本实验中,我们将学习如何在 C++ 中打印一个反向半金字塔图案。我们将使用两种不同的方法来实现这一目标,一种使用星号(*),另一种使用数字。
在本实验中,我们将学习如何在 C++ 中打印一个反向半金字塔图案。我们将使用两种不同的方法来实现这一目标,一种使用星号(*),另一种使用数字。
首先,我们需要在 ~/project
目录下创建一个新的 C++ 文件。我们可以将其命名为 main.cpp
。要创建新文件,请打开终端并输入以下命令:
cd ~/project
touch main.cpp
在这一步中,我们将编写一个 C++ 程序来使用星号(*)打印反向半金字塔图案。为此,我们需要使用嵌套的 for 循环。外层循环用于遍历行,内层循环用于在每行打印星号。
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) {
for(int j = 1; j <= i; ++j) {
cout << "* ";
}
cout << "\n";
}
return 0;
}
要运行此程序,我们需要编译并执行它。为此,我们需要在终端中输入以下命令:
g++ main.cpp -o main && ./main
这将编译程序并执行它,输出将显示在终端中。
在这一步中,我们将编写一个 C++ 程序来使用数字打印反向半金字塔图案。为此,我们需要在前一个程序的内层循环中将星号替换为数字。
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) {
for(int j = 1; j <= i; ++j) {
cout << j << " ";
}
cout << "\n";
}
return 0;
}
要运行此程序,我们需要编译并执行它。为此,我们需要在终端中输入以下命令:
g++ main.cpp -o main && ./main
这将编译程序并执行它,输出将显示在终端中。
完成上述步骤后,我们的 main.cpp
文件将包含以下代码:
#include <iostream>
using namespace std;
int main() {
int rows;
// 使用星号(*)打印反向半金字塔
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) {
for(int j = 1; j <= i; ++j) {
cout << "* ";
}
cout << "\n";
}
// 使用数字打印反向半金字塔
cout << "Enter number of rows: ";
cin >> rows;
for(int i = rows; i >= 1; --i) {
for(int j = 1; j <= i; ++j) {
cout << j << " ";
}
cout << "\n";
}
return 0;
}
在本实验中,我们学习了如何使用两种不同的方法在 C++ 中打印反向半金字塔图案——使用星号(*)和使用数字。我们通过嵌套的 for 循环实现了这一图案。此外,我们还学习了如何在终端中编译和运行 C++ 程序。