法一:星星行数 n 为奇数
#include <iostream>
using namespace std;
#include <cmath>
int main()
{
cout << "请输入要打印的星星的行数:" << endl;
int n;
cin >> n;
for (int i = -(n-1)/2; i <= (n-1)/2; i++)
{
for (int j = 1; j <= abs(i); j++)
{
cout << " ";
}
for (int j = 1; j <= n - 2 * abs(i); j++)
{
cout << "* ";
}
cout << endl;
}
system("pause");
return 0;
}
法二:星星行数 n 不区分奇偶
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "请输入奇数星星行数:" << endl;
cin >> n;
for (int i = 1;i <= n;i++)
{
if (i <= (n - 1) / 2)
{
for (int j = 1;j <= (n+1)/2-i;j++)
{
cout << " ";
}
for (int k = 1;k <= 2 * i - 1;k++)
{
cout << "* ";
}
cout << endl;
}
else
{
for (int j = 1;j <= i - (n+1)/2;j++)
{
cout << " ";
}
for (int k = 1;k <= 2 * (n - i) + 1;k++)
{
cout << "* ";
}
cout << endl;
}
}
system("pause");
return 0;
}