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

时间:2015-08-06 08:28:57

标签: c cs50

我试图在C中编写一个Mario半金字塔,但我的代码没有做任何事情。 我最初搞乱了断路器,它把所有东西颠倒过来,当我修复它时,它只是要求输入而不做任何其他事情。

#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");                  
    }
};

1 个答案:

答案 0 :(得分:0)

如果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");
}

并获得输出:

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