1027 打印沙漏 (20分)
本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印
*****
***
*
***
*****
所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。
给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。
输入格式:
输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。
输出格式:
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。
输入样例:
19 *
输出样例:
*****
***
*
***
*****
2
程序代码:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
int main()
{
int count=0;
string str;
cin>>count>>str;
//n:表示从沙漏尖端"*"到沙漏顶端的行数
int n=0;
n=sqrt((count+1)/2);
//打印上层沙漏,i:表示当前打印沙漏的行数序号
for (int i=0;i<n;i++)
{
//字符" "与行数序号的关系
for (int j=0;j<i;j++)
{
cout<<" ";
}
//字符"*"与行数序号的关系
for (int j=0;j<2*(n-i)-1;j++)
{
cout<<str;
}
cout<<endl;
}
//打印下层沙漏
for (int i=1;i<n;i++)
{
for (int j=0;j<(n-i-1);j++)
{
cout<<" ";
}
for (int j=0;j<2*i+1;j++)
{
cout<<str;
}
cout<<endl;
}
cout<<count-(2*n*n-1);
return 0;
}