L1-002 打印沙漏

很容易发现,当层数是k的时候,这一层的有2k-1个。
结合数列求和公式,以及上下对称总的
数量为(1+2k-1)k/22-1=2k*k-1
所以第一步计算出来多少层,就很好做了,第i层对应的空格数量就是层数-i。
代码:

#include <bits/stdc++.h>
using namespace std;
int tot;
char c;
int main(){
	cin >> tot >> c;
    int row = 1;
    for(int i=1;;i++){
    	if(2*i*i-1>tot){
    		row = i-1;
    		break;
		}
	}
	int rest = tot - (2*row*row-1);
	for(int i=row;i>0;i--){
		for(int j=0;j<row-i;j++) cout << ' ';
		for(int j=0;j<2*i-1;j++) cout << c;
		cout << endl;
	}
	for(int i=2;i<=row;i++){for(
	    int j=0;j<row-i;j++) cout << ' ';
		for(int j=0;j<2*i-1;j++) cout << c;
		cout << endl;
	}
	cout << rest << endl;
	return 0;
}
posted @ 2024-03-07 11:56  YuKiCheng  阅读(25)  评论(0编辑  收藏  举报