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

标签 c cs50

我试图用 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/

相关文章:

objective-c - OBJ-C : NSStrings - stringByAppendingString method

c - 枚举数组时遇到问题

地穴暴力永无休止的循环

c - 我的错误在哪里? CS50贪婪.c

java - 尽管构建没有错误,CS50 Android Track Filter 将无法在设备中运行

c - 4 个字符破解速度很快,但添加第 5 个循环会减慢整个程序的速度

c - 类型转换类型是否取决于大/小端?

c - char a[] ="string"之间的区别;字符 *p ="string";

c - 迭代 PEB DllName 仅显示 exe 名称

c - 我的代码不打印名为 coin 的变量