代码如下
#include <stdio.h>
//以等差数列看待沙漏,从中间往上每一行符号数为(2 × 行数 - 1)
int main() {
int N;
char sign;
scanf("%d %c", &N, &sign);
int n = 0;
int rowNum,sum; //沙漏一半的行数、到该行为止有多少符号(等差数列求和)
for (int i = 1; i <= 1000; i++) {
sum = (1 + 2 * i - 1)*i / 2; //等差数列求和
if (2 * sum - 1 > N) {
rowNum = i - 1;
break;
}
}
//从上开始打印
int spaceNum = 0; //空格数
for (int i = rowNum; i > 0; i--) {
int temp = spaceNum;
while (temp-- > 0) {
printf(" ");
}
int thisRow = 2 * i - 1;//该行符号数
while (thisRow-- > 0) {
printf("%c", sign);
}
temp = spaceNum;
/*while (temp-- > 0) { //注意不要打印右边空格!!!
printf(" ");
}*/
printf("\n");
spaceNum++;
}
spaceNum = (2 * rowNum - 1 - 3) / 2; //沙漏下半部分从3颗*开始,则空格数为沙漏最上 满* 的一行减去这3颗*,再除以2
for (int i = 2; i <= rowNum; i++) {
int temp = spaceNum;
while (temp-- > 0) {
printf(" ");
}
int thisRow = 2 * i - 1;
while (thisRow-- > 0) {
printf("%c", sign);
}
temp = spaceNum;
/*while (temp-- > 0) { //注意不要打印右边空格!!!
printf(" ");
}*/
printf("\n");
spaceNum--;
}
sum = (1 + 2 * rowNum - 1)*rowNum / 2;
printf("%d\n", N - (2 * sum - 1));
return 0;
}
一定要注意的是不要打印右边的空格,否则会出现“格式错误”。