在if语句中使用while语句循环

时间:2013-10-31 22:34:53

标签: c

所以在我的代码中,如果你低估或高估,你必须猜一个数字。如何让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;
    }
}

2 个答案:

答案 0 :(得分: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。将其替换为else,因为这是唯一剩下的情况。

答案 1 :(得分: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的返回值,以确定该号码是否已成功读取。