B1027 打印沙漏 (20 分)

最重要的公式推导,等差数列,求和公式。

#include <iostream>
#include <math.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
    
    
	int n;
	char c;
	cin >> n >> c;
	
	//运用公式
	int x = (int)sqrt(2.0*(1+n))-1;
	if(x % 2 == 0){
    
    
		x--;
	}
	int line = (x+1)/2;
	int use = (x+1)*(x+1)/2-1;
	//打印倒三角
	for(int i = x; i >= 0; i-=2){
    
    
		for(int j = 0; j < (x - i)/2; j++){
    
    
			cout << " ";
		}
		for(int j = 0; j < i; j++){
    
    
			cout << c;
		}
		cout << endl;
	} 
	
	//打印正三角
	for(int i = 3; i <= x ; i+=2){
    
    
		for(int j = 0; j < (x - i)/2; j++){
    
    
			cout << " ";
		}
		for(int j = 0; j < i; j++){
    
    
			cout << c;
		}
		cout << endl;
	} 
	printf("%d", n-use);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/alovelypeach/article/details/113971310