【问题标题】:do-while loop evaluating two if and else if statements. One regardless of inputs. (C)do-while 循环评估两个 if 和 else if 语句。一个不管输入。 (C)
【发布时间】:2015-02-20 04:17:59
【问题描述】:

下面是我的代码,基本上我试图让我的 do-while 循环运行,只要 if 或 else if 语句被评估为真。但是每次我运行它时,它都会起作用,只是它总是打印 2 else if 语句“您输入的值小于 1”,而不管用户输入如何。我完全不知道为什么它错了。

int get_input(void){

    int Value_1;
    int status;
    do{

        //Ask user to enter an odd number between 1 and 9
        printf("Enter any odd number between 1 and 9 inclusive> \n");
        //Store entered number in Value_1

        status = scanf(" %d", &Value_1);
        is_valid(Value_1);
  }
    while (is_valid()!=1);
    return(Value_1);
}

int is_valid(int status){

    if(status==2 || status==4 || status==6|| status==8){

        printf("The value you entered is not odd>\n");
        return(0);
    }
    else if(status > 9){
        printf("the value you entered is greater than 9> \n");
        return(0);
}
    else if(status < 1){
        printf("the value you entered is less than 1> \n");
        return(0);
}
    else{
        return(1);
    }
}

int main(void){


    int Value_1;
    int status;


    Value_1=get_input();
    printf("%d", Value_1);
  return(0);
}

【问题讨论】:

  • 您确定您的代码甚至可以编译吗?您正在调用一个带有 no 参数的函数。

标签: c if-statement do-while


【解决方案1】:

删除这个

is_valid(Value_1);

改变

while (is_valid()!=1);

while (is_valid(Value_1)!=1);

您遇到的问题是,在您的 while 中,is_valid() 没有任何参数,这会导致错误。

【讨论】:

    【解决方案2】:

    在 while 语句中,您正在调用不带参数的函数。做那个 像这样。

     while (is_valid(value_1)!=1);
    

    删除块内的调用。因为你两次调用同一个函数。这就是它打印两次的原因。

    并制作函数的函数原型,在此之前,

    int is_valid(int status);
    int get_input(void){
     ...
     ...
    }
    

    编译器没有定义函数的方式。如果你放置这个,你会得到这个错误。

    too few arguments to function ‘is_valid’
    

    【讨论】:

      【解决方案3】:

      替换

      do{
      
              //Ask user to enter an odd number between 1 and 9
              printf("Enter any odd number between 1 and 9 inclusive> \n");
              //Store entered number in Value_1
      
              status = scanf(" %d", &Value_1);
              is_valid(Value_1);
        }
        while (is_valid()!=1);
      

      do{
      
              //Ask user to enter an odd number between 1 and 9
              printf("Enter any odd number between 1 and 9 inclusive> \n");
              //Store entered number in Value_1
      
              scanf(" %d", &Value_1);
             status =  is_valid(Value_1);
        }
          while (status!=1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-18
        • 2015-11-08
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-07
        相关资源
        最近更新 更多