PAT-B-1027-打印沙漏

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

1
2
3
4
5
*****
***
*
***
*****

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

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

输入格式:

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

输出格式:

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

输入样例:

1
19 *

输出样例:

1
2
3
4
5
6
*****
***
*
***
*****
2

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//先把数学公式列出来计算一遍
#include <iostream>
#include <cmath>
using namespace std;

int main(){
int n;
char c;
scanf("%d %c", &n, &c);

int bottom = (int)sqrt(2.0 * (n + 1)) - 1;
if (bottom % 2 == 0)bottom--;//偶数时减1,令其为奇数
int count = (bottom + 1) * (bottom + 1) / 2 - 1;//计算出*的个数

int i, j;
//打印上三角
for (i = 0;i < bottom / 2 + 1;i++) {
for (j = 0;j < bottom - i;j++) {
if (j < i)
printf(" ");
else
printf("%c", c);
}
printf("\n");
}
//打印下三角
for (i = 3;i <=bottom;i+=2) {
for (j = 0;j < (bottom - i)/2;j++)
printf(" ");
for(j= 0;j < i;j++)
printf("%c", c);
printf("\n");
}
printf("%d\n", n - count);

return 0;
}

----\(˙<>˙)/----赞赏一下吧~