0

所以在我的代码中,如果你低估或高估了,你必须猜测一个数字。如何让 while 循环循环回输入,以便您可以输入另一个数字?

#include <stdio.h>

int main(int argc, const char * argv[])
{
    int number = 45;

    printf("Please insert a number");
    scanf("%d", &number);


    if (number == 45){
        printf("good job! You got the number right.");
        return 0;
    }
    else if (number < 45){
        while (number < 45 || number > 45){
            printf("Your number is too low");
            return 1;
        }
    }
    else if (number > 45){
        printf("Your number is too high!");
        return 1;
    }
}
4

2 回答 2

1

只需while (1)在您的代码周围加上一个并删除错误放置的那个:

#include <stdio.h>

int main(int argc, const char * argv[])
{
    while (1) {
        int number = 45;

        printf("Please insert a number");
        scanf("%d", &number);


        if (number == 45){
            printf("good job! You got the number right.");
            return 0;
        }
        else if (number < 45){
            printf("Your number is too low");
        }
        else{
            printf("Your number is too high!");
        }
    }
}

return正在关闭程序。因此,当用户没有猜到您的号码时,您不想返回。
while (1)是只有在启动时才会退出的循环return 0(当玩家获胜时)。

此外,else if不需要你的最后一个。将其替换为 a else,因为它是唯一剩下的情况。

于 2013-10-31T22:38:40.867 回答
1

用循环包装你的代码:

int number = 45;

while (1) {
    printf("Please insert a number");
    if (scanf("%d", &number) != 1) {
        printf("not valid number, try again");
        continue;
    }
    if (number == 45){
        printf("good job! You got the number right.");
        return 0;
    }
    if (number < 45){
        printf("Your number is too low");
        continue;
    }
    if (number > 45){
        printf("Your number is too high!");
        continue;
    }
}

请注意,您还应该检查返回值,scanf以了解该数字是否已成功读取。

于 2013-10-31T22:39:50.880 回答