【PAT-B1027】 打印沙漏 (20 分)(c++)

#include<iostream>
#include<string>

using namespace std;

void test()
{
	int num;
	string flag;

	int putout = 0;

	cin >> num;
	cin >> flag;

	int res = 0;
	int i = 1;

	//找出上三角的行数
	for ( i ; res < num; i++)
	{
		res = 2 * i * i - 1;
		//cout << i << "、" << res << endl;
		
		if (res >= num)
		{
			i = i - 1;
			if (res == num)
			{
				i = i + 1;
			}
			break;
		}
	}
	//cout << i << endl << endl;
	
	//开始打印 每一行
	int count = 0;//计数
	int start = 2 * i - 1;//以第一次的为主//例如五
	while (i > 0)
	{
		int temp = 0;

	/*	cout << 2 * i - 1 << " ";*/
		
		count = 2 * i - 1;
		//打印上三角
		//打印前空格
		temp = (start - count) / 2;
		for (int j = 0; j < temp; j++)
		{
			cout << " ";
		}
		//打印字符
		for (int j = 0; j < count; j++)
		{
			cout << flag;
			putout++;
		}

		cout << endl;
		i--;

	}

	//打印下三角
	int count_1 = 0;
	int k = 1;
	while (count_1 < start)
	{
		//剔除特殊情况
        if (start == 1)
        {
            break;
        }
        
		int temp = 0;
		count_1 = 2 * k + 1;
		temp = (start - count_1) / 2;
		for (int j = 0; j < temp; j++)
		{
			cout << " ";
		}
		//打印字符
		for (int j = 0; j < count_1; j++)
		{
			cout << flag;
			putout++;
		}
		
		cout << endl;
		k++;
	}
	cout << num - putout << endl;

}


int main()
{
	test();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值