如何强制用户在一定范围内输入正整数起始值

时间:2018-04-09 20:57:47

标签: c

如何修复我的代码,以便如果将起始值作为负整数输入,则会要求另一个起始值。此外,每次输入起始值和结束值时,计算差异的最佳方法是什么。

void inputs(int* starting_value, int* ending_value)
    {
      int temp; // switch for while loop

      temp = 0; // enter while loop

      while(temp == 0)
      {

        printf("Enter starting value of range -> ");
        scanf("%d", starting_value);

        do
        {
          printf("Error! Starting value must be non-negative!!\n");
          printf("\nEnter starting value of range -> ");
          scanf("%d", starting_value);
        } while(starting_value < 0); // if input is negative

        printf("Enter ending value of range -> ");
        scanf("%d", ending_value);

        temp = 1; // leave while loop

        if (ending_value - starting_value > 5000000) // if the total difference is less than 5000000
        {
          temp = 0; // restart while loop
          printf("\n\nError! The maximum difference between start and end is 5000000\n\n");
        }

      }
    }

1 个答案:

答案 0 :(得分:0)

将您的行为更改为仅在检查输入时,如果用户在第一次输入1时仍然会通过该重试逻辑。

最好的方法可能是同时获取两个输入,然后减去它们。

printf("Enter start and end variables\n");
scanf("%d %d", &start, &end);

while((start < 0) || (end < 0)){ //You can also throw a max range check here too
  printf("Enter start and end variables\n");
  printf("Make SURE neither value is negative\n");
  scanf("%d %d", &start, &end);
}

//subtract or do whatever else after both inputs are non negative