gpt4 book ai didi

c - 我的代码中的循环哪里出错了?

转载 作者:行者123 更新时间:2023-11-30 19:42:30 25 4
gpt4 key购买 nike

我试图用 C 语言编写一个马里奥半金字塔,但我的代码没有做任何事情。我最初搞砸了循环断路器,它把所有东西都颠倒了,当我修复它时,它只是要求输入而不做任何其他事情。

#include <cs50.h>
#include <stdio.h>

int main(void)
{
int height;
int space;
int rows;
int hashes;

// The code below decides if the users input meets the guide lines
do
{
printf("Enter the heigth of the pyramid here");
height = GetInt();
}
while (height <= 0 || height > 23);

for(rows = 1 ;rows > height ;rows++)
{
// the code gives the number of spaces per row
for(space = height - 1;space >= 1;space--)
{
printf(" ");
};

//The code below gives the number of hashes that have to be printed
for(hashes = height + 1 - space; hashes> 0; hashes--)
{
printf("#");
};

height = height + 1
printf("\n");
}
};

最佳答案

如果 height 不小于 1,则 for 循环不会迭代一次。

for(rows = 1 ;rows > height ;rows++)
{
//....

我修改了您的代码,如下所示 height = 5

for (rows = 1; rows <= height; rows++) {// iterate up to height times 
for (space = height - rows; space >= 1; space--) { // at first print spaces height -1 times. then spaces will be reduced by 1 from previous.
printf(" ");
};
// at first print hashes 2 times. then hashes will be increased by 1 from previous.
for (hashes = rows + 1; hashes > 0; hashes--) {
printf("#");
};
printf("\n");
}

并获取输出:

    ##
###
####
#####
######

关于c - 我的代码中的循环哪里出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31850612/

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