PAT B 1027 hourglass printing (20 minutes)

This question asks you to write a program to print a given symbol into an hourglass shape. 17 example given, "*", the following format printing requires

*****
 ***
  *
 ***
*****

The so-called "hourglass shape" refers to each row outputs odd symbols; symbol center of each row are aligned; the difference between the number of symbols two adjacent rows 2; the number of symbols in descending order of descending to the first one, then the order of small to large increments; inclusive symbol equal numbers.

Given any N symbols, not necessarily exactly composed of an hourglass. Requirements can be printed out as much of the hourglass symbol.

Input formats:

Input gives a positive integer N (≤1000) and a symbol in a row, separated by a space.

Output formats:

First print largest hourglass shape consisting of a given symbol, the symbol number output last remaining useless fall in a row.

Sample input:

19 *

Sample output:

*****
 ***
  *
 ***
*****
2
#include <iostream>
using namespace std;
int main()
{
	int n,sum=0,m,count=0,i;
	char c;
	cin>>n>>c;
	for(int k=1;k<=n;k+=2)
	{
		sum+=k;
		if(2*sum-1==n)
		{
			m=k;
			break;
		}
			
		if(2*sum-1>n)
		{
			sum-=k;
			k-=2;
			m=k;
			break;
		}
		count++;
	}
	int f=count;
	for(i=m;i>=1;i-=2)
	{
		for(int j=count;j<f;j++) cout<<" ";
		for(int k=i;k>0;k--) cout<<c;
		cout<<endl;
		count--;
	}
	count=2;
	for(i=3;i<=m;i+=2)
	{
		for(int j=count;j<f;j++) cout<<" ";
		for(int k=i;k>0;k--) cout<<c;
		cout<<endl;
		count++;
	}
	cout<<n-2*sum+1<<endl;
	return 0;
}

 

Published 38 original articles · won praise 1 · views 404

Guess you like

Origin blog.csdn.net/qq_40570410/article/details/104737659