编写一个 C++ 程序,使用 for 循环打印数字 8 星形图案。
#include<iostream>
using namespace std;
int main()
{
int rows;
cout << "Please Enter 8 Pattern Rows = ";
cin >> rows;
cout << "Printing 8 Pattern of Stars\n";
for (int i = 1; i <= rows * 2 - 1; i++)
{
if (i == 1 || i == rows || i == rows * 2 - 1)
{
for (int j = 1; j <= rows; j++)
{
if (j == 1 || j == rows)
{
cout << " ";
}
else
{
cout << "*";
}
}
}
else
{
for (int k = 1; k <= rows; k++)
{
if (k == 1 || k == rows)
{
cout << "*";
}
else
{
cout << " ";
}
}
}
cout << "\n";
}
}

C++ 使用 while 循环打印数字 8 星形图案的程序
#include<iostream>
using namespace std;
int main()
{
int rows, i, j, k;
cout << "Please Enter 8 Pattern Rows = ";
cin >> rows;
cout << "Printing 8 Pattern of Stars\n";
i = 1;
while (i <= rows * 2 - 1)
{
if (i == 1 || i == rows || i == rows * 2 - 1)
{
j = 1;
while (j <= rows)
{
if (j == 1 || j == rows)
{
cout << " ";
}
else
{
cout << "*";
}
j++;
}
}
else
{
k = 1;
while (k <= rows)
{
if (k == 1 || k == rows)
{
cout << "*";
}
else
{
cout << " ";
}
k++;
}
}
cout << "\n";
i++;
}
}
Please Enter 8 Pattern Rows = 10
Printing 8 Pattern of Stars
********
* *
* *
* *
* *
* *
* *
* *
* *
********
* *
* *
* *
* *
* *
* *
* *
* *
********
此程序使用 do while 循环打印星号的数字 8 图案。
#include<iostream>
using namespace std;
int main()
{
int rows, i, j, k;
cout << "Please Enter 8 Pattern Rows = ";
cin >> rows;
cout << "Printing 8 Pattern of Stars\n";
i = 1;
do
{
if (i == 1 || i == rows || i == rows * 2 - 1)
{
j = 1;
do
{
if (j == 1 || j == rows)
{
cout << " ";
}
else
{
cout << "*";
}
} while (++j <= rows);
}
else
{
k = 1;
do
{
if (k == 1 || k == rows)
{
cout << "*";
}
else
{
cout << " ";
}
} while (++k <= rows);
}
cout << "\n";
} while (++i <= rows * 2 - 1);
}
Please Enter 8 Pattern Rows = 13
Printing 8 Pattern of Stars
***********
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
***********
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
***********
在此示例中,star8Pattern 函数允许输入行数和字符,并打印给定字符的数字 8 图案。
#include<iostream>
using namespace std;
void Pattern8(int rows, char ch)
{
for (int i = 1; i <= rows * 2 - 1; i++)
{
if (i == 1 || i == rows || i == rows * 2 - 1)
{
for (int j = 1; j <= rows; j++)
{
if (j == 1 || j == rows)
{
cout << " ";
}
else
{
cout << ch;
}
}
}
else
{
for (int k = 1; k <= rows; k++)
{
if (k == 1 || k == rows)
{
cout << ch;
}
else
{
cout << " ";
}
}
}
cout << "\n";
}
}
int main()
{
int rows;
char ch;
cout << "Enter Character for 8 Pattern = ";
cin >> ch;
cout << "Please Enter 8 Pattern Rows = ";
cin >> rows;
cout << "Printing 8 Pattern of Stars\n";
Pattern8(rows, ch);
}
Enter Character for 8 Pattern = #
Please Enter 8 Pattern Rows = 15
Printing 8 Pattern of Stars
#############
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
#############
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
#############