我是C编程的初学者。 这是我的代码。但是我不知道如何解决。这很奇怪。出了点问题。请帮助我修复它!谢谢。
#include <stdio.h>
int main(void)
{
int num, n, r, c, sp;
scanf("%d", &num);
printf("\n");
n = num;
for (r = 1; r <= num; r++)
{
for (sp = 1; sp < r; sp++)
printf(" ");
for (c = 1; c <= n; c++)
printf("**");
n--;
printf("\n");
}
答案 0 :(得分:4)
始终首先绘制整洁的小图片并进行分析:
assume mid_height = 5
height = 2 * mid_height - 1
+---------------------------- = 0 ... height - 1
| +------------------- = line < mid_height ? line : height - line - 1
| | +---------- = height + 1 - spaces * 2
| | | +-- = mid_height <= line && line < height - 1
| | | |
| leading stars/ points
1234567890 line spaces points line
********** 0 0 10 no
******** 1 1 8 no
****** 2 2 6 no
**** 3 3 4 no
** 4 4 2 no
*..* 5 3 4 si
*....* 6 2 6 si
*......* 7 1 8 si
********** 8 0 10 no
之后,这只是一个写作练习:
#include <stdio.h>
int main(void)
{
int mid_height;
while (printf("Please enter the mid height of the hourglass: "),
scanf("%d", &mid_height) != 1 || mid_height < 1) {
fputs("Input error!\n\n", stderr);
int ch;
while ((ch = getchar()) != EOF && ch != '\n');
}
putchar('\n');
int height = 2 * mid_height - 1;
for (int line = 0; line < height; ++line) {
int spaces = line < mid_height ? line : height - line - 1;
int points_line = mid_height <= line && line < height - 1;
for (int w = 0; w < height + 1 - spaces; ++w) {
int points = points_line && w != spaces && w != height - spaces;
putchar(w < spaces ? ' ' : points ? '.' : '*');
}
putchar('\n');
}
}
Please enter the mid height of the hourglass: 5
**********
********
******
****
**
*..*
*....*
*......*
**********