【问题标题】:How to keep asking user to input until condition is satisfied in C?如何一直要求用户输入直到满足 C 中的条件?
【发布时间】:2021-01-13 07:20:18
【问题描述】:

这是一个小型 C 程序,我正在尝试验证用户输入。我希望用户输入 3 个值。条件是所有 3 个输入不应具有相同的值。那么如何循环用户输入直到满足条件(真)。这是代码。帮帮我,我是编程新手,谢谢。 :)

#include<stdio.h>

int main()
{
    int u1,u2,u3;
    
    printf("Enter 3 Numbers : ");  //Printing
    scanf("%d %d %d",&u1,&u2,&u3); //Asking for Input
    
    if(u1==u2 || u2==u3 || u3==u1)       //This is the condition
    {
        printf("Condition is not Satisfied !");      
    }
}

那么我该如何循环它。谢谢。

【问题讨论】:

  • 你听说过do-while循环吗? a,b,c 是什么?
  • @TonyTannous 是的..我知道我们必须使用循环..我很困惑如何去做..我是菜鸟
  • 我再问,a,b,c是什么?
  • 搞错了.. 抱歉
  • 您的要求是所有三个不能是相同的值,但您的代码说只有两个或三个可能相等。

标签: c loops if-statement while-loop user-input


【解决方案1】:

我建议您使用以下代码:

#include <stdio.h>

int main( void )
{
    int u1,u2,u3;

    for (;;) //infinite loop, equivalent to while(true)
    {
        printf( "Enter 3 Numbers: " );
        scanf( "%d %d %d", &u1, &u2, &u3 );

        if ( u1!=u2 && u2!=u3 && u3!=u1 ) break;

        printf( "Error: Condition is not satisfied!\n" );
    }
}

与其他答案之一相比,此解决方案的优点是每次循环迭代只检查一次条件。

但是,上面的代码(以及大多数其他答案的代码)有一个严重的问题:如果用户输入字母而不是数字,程序将陷入无限循环。这是因为在不检查返回值的情况下调用scanf 是不安全的。有关不安全原因的更多信息,请参阅以下页面:A beginners' guide away from scanf()

【讨论】:

    【解决方案2】:

    一种非常不完美的方法是借助递归而不是循环(注意 cmets):

    #include <stdio.h>
    
    // Recursive function to verify if all the three are unequal
    void is_satisfied(int v1, int v2, int v3) {
      printf("Input three different values: ");
      scanf("%d %d %d", &v1, &v2, &v3);
    
      if (v1 != v2 && v2 != v3 && v3 != v1)
        return; // Exiting from the recursion
      else {
        // If any of the three condition stated in the IF statement
        // is true, then clearly not satisfied
        printf("Nope! It is not satisfied...\n");
        is_satisfied(v1, v2, v3);
      }
    }
    
    int main(void) {
      int first = 0, second = 0, third = 0;
    
      // Using the recursion
      is_satisfied(first, second, third);
    
      // Hooray! All done...
      return 0;
    }
    

    【讨论】:

      【解决方案3】:

      试试这个,

      #include<stdio.h>
      
      int main()
      {
          int u1,u2,u3;
          
          while(u1==u2 || u2==u3 || u3==u1)  //This is the condition
          {
              printf("Enter 3 Numbers : ");  //Printing
              scanf("%d %d %d",&u1,&u2,&u3); //Asking for Input
              
              if(u1==u2 || u2==u3 || u3==u1) 
                  printf("Condition is not Satisfied !\n");    
              else
                  break;
          }
          return 0;
      }
      

      【讨论】:

      • 每次循环迭代两次检查完全相同的条件似乎不必要的麻烦。请参阅我的答案以获取仅检查一次条件的替代方法。
      猜你喜欢
      • 1970-01-01
      • 2015-06-27
      • 2022-12-18
      • 2019-03-02
      • 2022-11-23
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      相关资源
      最近更新 更多