题目:
思路:
1.找到打印字符个数的规律,每行为基数个数,2n-1。总体呈对称形式,需要的个数为2n**2-1
2.获取一半的总行数,n=floor(sqrt((所给个数+1)/2))
3.获取每行打印内容,N-n个空格,以及n个给定字符(代码示例中注释与非注释部分为两种打印方式)
4.按行输出
代码:
# include<iostream>
# include<cstring>
# include<cmath>
using namespace std;
string show(int n,string str,int N)
{
string s="";
for(int i=1;i<=N-n;i++)
{
s += " ";
}
for(int i=1;i<=2*n-1;i++)
{
s += str;
}
return s;
}
string show2(int n,char chr,int N)
{
string s="";
s.append(N-n,' ');
s.append(2*n-1,chr);
return s;
}
string show2(int n,char chr,int N);
string show(int n,string str,int N);
int main()
{
int Num=0,sum=0,n=0;
// string ch="";
// cin>>Num>>ch;
// n = floor(sqrt((Num+1)/2));
// sum = Num-2*n*n+1;
// for(int i=n;i>0;i--)
// {
// cout<<show(i,ch,n)<<endl;
// }
// for(int j=2;j<=n;j++)
// {
// cout<<show(j,ch,n)<<endl;
// }
char ch;
cin>>Num>>ch;
n = floor(sqrt((Num+1)/2));
sum = Num-2*n*n+1;
for(int i=n;i>0;i--)
{
cout<<show2(i,ch,n)<<endl;
}
for(int j=2;j<=n;j++)
{
cout<<show2(j,ch,n)<<endl;
}
cout<<sum<<endl;
return 0;
}
结果:
PLUS:
其它的解法(搬运):
https://blog.csdn.net/weixin_53230235/article/details/120242764
https://blog.csdn.net/wmjtxt/article/details/58678097