编写一个 C++ 程序,使用 for 循环打印金字塔数字模式。
#include<iostream>
using namespace std;
int main()
{
int rows;
cout << "Enter Pyramid Number Pattern Rows = ";
cin >> rows;
cout << "Printing Pyramid Number Pattern\n";
for (int i = 1; i <= rows; i++)
{
for (int j = rows; j > i; j--)
{
cout << " ";
}
for (int k = 1; k <= i; k++)
{
cout << i << " ";
}
cout << "\n";
}
}

此程序有助于使用 while 循环打印金字塔数字模式。
#include<iostream>
using namespace std;
int main()
{
int rows, i, j, k;
cout << "Enter Rows = ";
cin >> rows;
cout << "Printing\n";
i = 1;
while (i <= rows)
{
j = rows;
while (j > i)
{
cout << " ";
j--;
}
k = 1;
while (k <= i)
{
cout << i << " ";
k++;
}
cout << "\n";
i++;
}
}
Enter Rows = 8
Printing
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
此 示例 使用 do while 循环显示数字金字塔模式。
#include<iostream>
using namespace std;
int main()
{
int rows, i, j, k;
cout << "Enter Rows = ";
cin >> rows;
i = 1;
do
{
j = rows;
do
{
cout << " ";
} while (j-- > i);
k = 1;
do
{
cout << i << " ";
} while (++k <= i);
cout << "\n";
} while (++i <= rows);
}
Enter Rows = 9
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9