1027 打印沙漏 (20分)
程序员文章站
2022-06-08 08:25:46
...
用两个循环去输出,以最中间为分界点
代码如下:
#include<stdio.h>
int main()
{
int n, i,sum=0,k,j;
char c;
scanf("%d %c", &n,&c);
for (i = 1; i < n; i = i + 2)
{
sum += i;
if ((2 * sum - 1) > n) break;
}
if (i > 3) {//分情况,当输入的n小于3时
sum = 2 * (sum - i) - 1;
for (j = i - 2; j >= 1; j = j - 2)
{//以最中间为分界点先输出它上方的
for (k = i - 2; k > j; k = k - 2) printf(" ");
for (k = j; k > 0; k--) printf("%c", c);
printf("\n");
}
for (j = 3; j <= i - 2; j = j + 2)
{//以最中间为分界点输出它下方的
for (k = i - 2; k > j; k = k - 2) printf(" ");
for (k = j; k > 0; k--) printf("%c", c);
printf("\n");
}
printf("%d", n - sum);
}
else
printf("%c\n%d", c, n - 1);
return 0;
}