【问题标题】:How to prompt the user to enter a integer within a certain amount of numbers如何提示用户输入一定数量内的整数
【发布时间】:2014-03-13 06:50:33
【问题描述】:

我试图弄清楚使用什么语句让用户输入 1 到 10 之间的数字。

这是我目前所拥有的。

int a;
printf("Enter a number between 1 and 10: \n);
scanf("%d", &a);

【问题讨论】:

  • 您无意中用标签回答了自己的问题 - 使用“while-loop”。
  • 而这个问题是......?

标签: c loops if-statement while-loop


【解决方案1】:

为什么不使用do .. while 循环?

int a;

do {
  printf("Enter a number between 1 and 10: \n");
  scanf("%d", &a);
} while (a < 1 || a > 10);

【讨论】:

    【解决方案2】:
    int input;
    
    while (true){
        scanf("%d",&input);
        if (input>=1 && input<=10){
            // process with your input then use break to end the while loop
        }
        else{
            printf("Wrong input! try Again.");
            continue;
        }
    }
    

    【讨论】:

    • 这是一个非常糟糕的设计。最好在输入无效时循环,然后再处理处理。也意味着您可以摆脱人工循环条件并在input 上循环。附带说明一下,C 代码中出现continue 几乎总是表明设计不佳。
    【解决方案3】:

    1 到 10 之间的数字对吗?所以第一阶段您必须验证输入是否为整数,然后您将检查范围,

    下面的代码是我提到的

    #define MAX_RANGE 10
    int input;
    if (scanf("%d",&input) != 1) 
    {
        printf ("Really bad input please enter integer number like in range 1 - 10\n");
    
    }
    

    现在第二阶段如下

    if (input < 1 || input > MAX_RANGE) {
       printf("It's an integer but out of range error\n");
    }
    

    您也可以使用while..loop,如下所示

    int input;
    
    while (scanf("%d", &input) == 1 && input > 1 && input < 10)
    
    {
    
        // process your input
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      相关资源
      最近更新 更多