主要是找到菱形的规律,看每行需要的空格和星号有多少。
#include<iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n; cin >> n;
if (n <= 1 || n >= 100) return 0;
for (int i = 1; i <= n; ++i)//前n行
{
for (int j = 1; j <= n - i; ++j)
{
cout << " ";
}
for (int k = 1; k <= 2*i-1; ++k)
{
cout << "*";
}
cout << '\n';
}
for (int i = n - 1; i > 0; --i)//后面n-1行
{
for (int j = 1; j <= n - i; ++j)
{
cout << " ";
}
for (int k = 1; k <= 2 * i - 1; ++k)
{
cout << "*";
}
cout << '\n';
}
return 0;
}