gpt4 book ai didi

c - 为什么这个 C 程序不显示星号金字塔?

转载 作者:行者123 更新时间:2023-11-30 21:08:10 24 4
gpt4 key购买 nike

我必须制作一个仅使用 while 循环打印星号金字塔的程序

   *
***
*****
*******

我目前有这个:

/* JJJ */
#include<stdio.h>
main()
{
int k;
clrscr();

printf("Enter the number of rows of the pyramid: ");
scanf("%d", &k);
int i=1;
while (i<=k)
{
int h=1;
printf("");
while (k>i)
{
printf(" ");
k--;
}
while (h<=2*i-1)
{
printf("*");
h++;
}
i++;
printf("\n");
}
getch();
}

它只打印一个星号。

最佳答案

您在打印空格的循环 while (k>i) 中错误地修改了 k 的值。您的代码仅显示一个星号的原因是在这个循环的迭代中,k的值减小到1。因此,在最外层循环的第一次迭代之后,到达终点。 查看此解决方案:

♦ 要在第 1 行打印的星号 (x) 数量。 k = 2 * k - 1
❖ x 个星号之前要打印的空格数 = k - (x/2)

int k, i=1, x,y;
printf("Enter no. of lines of the pyramid\n");
scanf("%d", k);

while(i <= k){
x = 2*i - 1, y=1;
while(y <= k - (x/2)){
printf(" ");
y++;
}
y=1;
while(y <= x){
printf("*");
y++;
}
printf("\n");
i++;
}

关于c - 为什么这个 C 程序不显示星号金字塔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40055014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com