Pset 1(Mario Less Hard)

时间:2020-06-07 02:24:07

标签: c cs50

该程序不运行,只是询问高度,然后没有任何东西继续前进。当我运行50时,它指示我接受foo和其他a之类的值,所以我用scanf替换了printf,一切都停止了工作。

还可以有人指导我如何使该程序不断询问2到8之间的高度,直到其正确吗?到目前为止,它会发出一条消息,输入2到8之间的一个数字,然后停止。

int main()
{
    int height;
    do {
        height =get_int("Height: ");
        scanf("%d", &height);

        if ( height<1 || height>8) { 
            printf ("Kindly Enter A Number Between 2 & 8 !\n"); 
            return 0;
        }

    }
    while (height <1 || height>8);

    for(int i=0; i<height ; i++) // Row Number
    {
        for (int j=0; j<height ;j++)
        {
            if (i+j >= height-1)
            printf("#");

            else 
                printf (" ");
        }
        printf("\n");
    }

}

2 个答案:

答案 0 :(得分:0)

删除return 0;语句中的if语句。 return函数中的main条语句立即终止程序。

答案 1 :(得分:0)

为什么两次服用height

        height =get_int("Height: ");
        scanf("%d", &height);

这就足够了:scanf("%d", &height);

还要始终检查scanf的返回。

并如前所述删除return 0,因为否则到达该目录时,您的程序将立即结束。

我认为您想要的是这样的

    int height;
    do {
        if (scanf("%d", &height) == 1);//checking the result of scanf function
        else
            exit(EXIT_FAILURE);

        if (height < 1 || height>8) {
            printf("Kindly Enter A Number Between 2 & 8 !\n");
            //removing return 0
        }

    }
    while (height < 1 || height>8);