L1-002 打印沙漏 (20分)

在这里插入图片描述

#include <iostream>
using namespace std;
/*求和公式s = n * a1 + n * (n-1)/2 * d*/ 
int main(){
	int n;char ch;
	cin >> n >> ch;
	int c = 0;
	while(2 * c * c + 4 * c + 1 <= n)
	  c++;
	
	//  cout << c << endl;
	  int kg = 0;
	  int gs = 1 + (c - 1) * 2;
	for(int i = 1; i <= c; i++){
		for(int j = 1; j <= kg;j++) 
			cout << " ";
		kg++;
		
		for(int k = 1; k <= gs;k++) 
			cout << ch;
		gs -= 2;
		cout << endl;	
	}
//	cout << kg << endl;
	kg-=2;gs+=2;
//	cout << kg << " " << gs << endl;
	for(int i = 2; i <= c; i++){
		gs += 2;
		for(int j = 1; j <= kg;j++)
			cout << " ";
		kg--;
		for(int k = 1; k <= gs;k++) 
			cout << ch;
		
		cout << endl;
		
	}
	cout << n - 2 * c * c  + 1 << endl;
	return 0;
} 
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页