L1-002 打印沙漏
本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印
*****
***
*
***
*****
所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。
给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。
输入格式:
输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。
输出格式:
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。
输入样例:
19 *
输出样例:
*****
***
*
***
*****
2
算一共几行,第一行几个就行
#include <cmath>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
static const auto io_sync_off = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
int main()
{
//ofstream fout("1.txt");
int num;
char c;
cin >> num >> c;
int n = sqrt((num + 1) / 2); //等差数列和求n
int first, line = 2 * n - 1; //第一行的个数
first = line;
for (int i = 1; i <= 2 * n - 1; ++i)
{
int temp = (first - line) / 2; //打印空格
while (temp)
{
--temp;
cout << " ";
}
if (i == n)
cout << c; //中间一行
else
for (int j = line; j >= 1; --j) //其他行
cout << c;
if (i < n)
line -= 2; //上半部分
else
line += 2; //下半部分
cout << endl;
}
cout << num - 2 * n * n + 1;
return 0;
}