简体   繁体   English

为什么我的while循环不会在此C代码中启动?

[英]Why won't my while loop initiate in this c code?

I'm new at programming in c but I just don't understand why this code won't run properly after compiling. 我是C语言编程的新手,但是我不明白为什么编译后此代码无法正常运行。 For now, I just want it to take numbers between 10 and 100 without errors. 现在,我只希望它取10到100之间的数字而不会出错。 Then later I'll add return 1 for errors and 0 for success. 然后,我将为错误添加return 1,为成功添加0。

#include <stdio.h>
#include <stdlib.h>

int intGet(int, int);
int error();

int main(void)
{
    int Min, Max, UserIn;
    Min = 10;
    Max = 100;

    printf("Enter a number in between [10 -­100]: \n");
    scanf("%d", &UserIn);
    printf("Read %d\n", UserIn);

    while (UserIn < Min && UserIn > Max)
    {
        printf("Invalid \n");
        scanf("%d", &UserIn);
    }
    /* What I did to fix
      while ((UserIn > Min) || (UserIn < Max)){
         printf("Enter a number in between [10 -­100]: \n");
         scanf("%d",&UserIn);       
         printf("Read %d\n",UserIn);

       while ((UserIn < Min) || (UserIn > Max)){
         printf("Invalid \n");
         scanf("%d", &UserIn);
          printf("Read %d\n", UserIn);


       }
      }*/

    return EXIT_SUCCESS;
}

int intGet(int min, int max)
{

}

int error()
{

}

while (UserIn < Min && UserIn > Max)

userIn can never meet both conditions. userIn不能同时满足这两个条件。 Change it to: 更改为:

whihe (userIn < Min || userIn > Max)

You do realise that scanf does return a value? 您确实意识到scanf确实会返回值吗? See http://linux.die.net/man/3/scanf 参见http://linux.die.net/man/3/scanf

If it does not return 1 then you need to "eat" some input. 如果它不返回1,那么您需要“吃掉”一些输入。

Better to read in a string and parse that. 最好阅读一个字符串并进行解析。

Also

while (UserIn < Min && UserIn > Max)

should be 应该

while (UserIn < Min || UserIn > Max)

replace 更换

while (UserIn<Min && UserIn>Max){

with: 与:

while (UserIn<Min || UserIn>Max){

also you can replace your while loop with do ... while. 你也可以用do ... while代替while循环。 then you will not have double scanf 那么您将不会再进行两次scanf

To help you debug this, try this code: 为了帮助您调试此代码,请尝试以下代码:

while ((UserIn < Min) || (UserIn > Max))
{
    printf("Invalid \n");
    scanf("%d", &UserIn);
    printf("Read %d\n", UserIn);
}

Also, this while loop will only run if the first inputted value for Userin was < 10 or > 100. 此外,仅当Userin的第一个输入值小于10或大于100时,才会运行while循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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