如下为打印沙漏的代码 :
#include<stdio.h>
#pragma warning(disable:4996)
void shaShape(int a, char b)
{
//求出它的最外层的*数
//规律 (n*2n)-1
//int n =a/n;
int n = 1;
while (1)
{
if ((a >= (2 * n * n) - 1) && (a < 2 * (n + 1) * (n + 1) - 1))
{
break;
}
n++;
}
//printf("%d", n);
//打印 最外层的为2n-1 5 3 1 3 5 49
//*****
// ***
// *
// ***
//*****
int xing = n;
int kong = n-2;
//int kong_xia = n-1;
int kong_xia2 = (2 * n - 1-3) / 2;
int xing_xia = 3;
for (int i = 0;i < 2 * n - 1;i++)//打印 5层
{
if (xing != 0)
{
for (int j = 0;j < i;j++)
{
printf(" ");
}
for (int k = 0;k < 2 * xing - 1;k++)// i=0 xing 3 i 1 xing 2 i=2
{
printf("%c",b);
}
printf("\n");
xing--;
}
//下半部分
/*else
{
for (int g=i;g < n+1;g++)
{
printf(" ");
}
for (int k=0;k < (2*kong+1);k++)
{
printf("%c",b);
}
printf("\n");
kong++;
}*/
/*
* 2 3 0 3 4 1 3 5 2 3 6 1 5 07 n=5
*** 0 ***** ******* 0 ********* 0
* 1 *** ***** 1 ******* 1
*** 2 * *** 2 ***** 2
*** 3 * 3 ***3
***** *** 4 2 *4
***** 1 *** 5
******* 0 *****
*******
*********
*/
//下半部分
else
{
// //空格 从 n-2 开始 到 等于0结束 i=3 i =2
//for (; kong_xia < i ;kong_xia++)
//{
// printf(" ");
//}
//kong_xia++;
//从
//2 1 0
for (int k = 0;k < kong_xia2;k++)
{
printf(" ");
}
kong_xia2--;
//打印*号 从3 开始打 递增+2
for (int x=0;x<xing_xia;x++)
{
printf("%c", b);
}
printf("\n");
xing_xia += 2;
}
}
printf("%d", a - (2 * n * n - 1));
}
int main()
{
int a;
char c;
scanf("%d %c", &a, &c);
shaShape(a, c);
return 0;
}