1027 打印沙漏 (20 分)
我的代码
// 1027 打印沙漏 (20 分).cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <math.h>
using namespace std;
int main(){
int i;
cin >> i;
char s;
cin >> s;
int num_total = 0;
int number_print = 0;
//算出第一行的个数
for (int j = 1; j < i / 2 - 1 ; j++) {
num_total = j * j * 2 - 1;
if (i <= num_total)
number_print++;
}
if (!number_print) {
cout << s << endl;
cout << i - 1;
return 0;
}
number_print = sqrt(number_print) + 1;//包含1的层数
//正序打印
for (int i = number_print - 1; i >= 0; i--) {
for (int j = 0; j < 2 * (i) + 1; j++){
j == 2 * (i) ? cout << s << endl : cout << s;
}
if (i == 0)
break;
for (int line = 0; line < number_print - i; line++) {
cout << " ";
}
}
//逆序打印
int number_pace = number_print - 1;
for (int i = 1; i < number_print; i++) {
for (int line = 1; line < number_pace; line++) {
cout << " ";
}
for (int j = 0; j < 2 * i + 1; j++) {
cout << s;
}
if (i != number_print - 1)
cout << endl;
number_pace--;
}
//计算差值
int size = number_print * number_print * 2 - 1;
if(i - size)
cout << "\n" << i - size;
}
思路
没什么难度,就是要注意好空格,换行的情况。