简体   繁体   中英

How to fix my code for cs50 pset 1 mario less comfortable

My solution to cs50 pset 1 (mario less comfortable) doesn't print out the pyramid. Instead it just prints out one #. I have tried this multiple times but all i get is errors when trying to compile saying it doesn't identify int i or that the semi-colon should be moved to a new line. Once i changed to this code the errors finally stopped and it takes input correctly but it doesn't print the pyramid.

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

int main(void)
{
int height;
int spaces;
int hashes;
int row;

do
{
    printf("Height: ");
    height = get_int();
}

while (height < 0 || height > 23);

for (row = 1; row <= height; row++)
    ;
{

    for (spaces = (height - 1) - row; spaces >= 0; spaces--)
        ; 
    {
        printf(" ");
    }

    for (hashes = 2; row < hashes; hashes++)
        ;
    {
        printf("#");
    }
    printf("\n");
}

}

This is the output in the terminal

$ make mario clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow mario.c -lcrypt -lcs50 -lm -o mario $ ./mario Height: 15 #

Your main problem is the semicolons after the for loops. Those form the body of the for loop, so the loop doesn't do anything. So in other words, this here

for (spaces = (height - 1) - row; spaces >= 0; spaces--)
        ;
    {
        printf(" ");
    }

Just turns into

{
    printf(" ");
}

And likewise for the other two for loops. That's why the things that you want to happen in a loop only happen once each: what you thought was the body of the for loop actually has nothing to do with said loop, so it just gets run once.

Also, the loop condition here

for (hashes = 2; row < hashes; hashes++)

Is wrong, it should be the other way around. You probably want something similar to this:

for (hashes = 2; hashes < row*2; hashes++)

Finally, int main should return an int, so add return 0; to the end of the function.

User Blaze alerady gave a perfect explanation of what is going on. I would like to add the following for clarity:

The syntax of the for-statement is roughly:

for ( ... ) <statement>

Where <statement> can be any statement, including the empty statement .

A semi-colon is a statement terminator . It indicates the end of a statement. If you write only a semi-colon, it terminates an empty statement . As a result, your loop body consisted out of the empty statement .

(As another example of the semi-colon as statement terminator: 2+2; which turns the expression into a statement.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM