PAT_自测1_打印沙漏

题目链接:https://pta.patest.cn/pta/test/17/exam/4/question/260

 

题面:

自测-1 打印沙漏   (20)

本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17“*”,要求按下列格式打印

*****

 ***

  *

 ***

*****

所谓沙漏形状,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。

给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。

输入格式:

输入在一行给出1个正整数N1000)和一个符号,中间以空格分隔。

输出格式:

首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。

输入样例:

19 *

输出样例:

*****

 ***

  *

 ***

*****

 

题目大意:

根据给定的字符数量,计算并输出一个沙漏

解题:

if N=1 直接输出并返回

if N>1, 先计算可以输出多少行,记最中心的为第0行,每多一行numPerLine= (2*lines + 1) * 2。算出行数lines rest后,从i=lines->0, i=1->lines输出。每行首的空格数space = lines-i

代码:

/**
* https://pta.patest.cn/pta/test/17/exam/4/question/260
* 数据结构练习 00-自测1. 打印沙漏(20)
给定任意N个符号,不一定能正好组成一个沙漏。
要求打印出的沙漏能用掉尽可能多的符号。
*/
#include <iostream>
using namespace std;

int main(){
	int num;
	char c;

	cin>>num>>c;

	if(num == 1){
		cout<<c<<endl;
		cout<<0<<endl;
		return 0;
	}
	//--Compute how many lines could be print
	int lines = 0, sum = 0;		// 2*lines+1 , lines>=0
	do{
		int numPerLine;
		if(lines==0)
			numPerLine = 1;
		else
			numPerLine = (2*lines + 1) * 2;

		// cout<<numPerLine<<"  "<<sum<<endl;
		if((sum + numPerLine) > num){
			lines--;
			break;
		}else{
			sum += numPerLine;
			lines ++;
		}
	}while(sum<num);

	// cout<<endl<<lines<<" "<<num<<" "<<sum<<endl;

	int rest = num - sum;

	for(int i = lines, space = lines-i ; i>=0; i--, space++){		//lines -> 0
		for(int j = 0; j<=lines; j++){
			if(j<space)					
				cout<<" ";
			else if(j==lines)			//should be the center one, ie the last printed one
				cout<<c<<endl;
			else
				cout<<c<<c;
		}
	}
	for(int i = 1, space = lines-i; i<=lines; i++, space--){		//1 -> lines
		for(int j = 0; j<=lines; j++){
			if(j<space)					
				cout<<" ";
			else if(j==lines)			//should be the center one, ie the last printed one
				cout<<c<<endl;
			else
				cout<<c<<c;
		}
	}
	cout << rest << endl;
	return 0;
}


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值