while循环输出不正确

时间:2015-06-20 05:44:46

标签: c while-loop

此函数要求loLimit和hiLimit之间的整数,并允许用户安全地输入它。它一直询问,直到用户输入合法范围内的数字。然后它返回合法号码。

NULL

但是,我的输出行为奇怪,好像loLimit值来回变化。此外,数字仅在输入两次后记录。

The correct output should be:
Please enter an integer between 32 and 127: 19
Please enter an integer between 32 and 127: 128
Please enter an integer between 32 and 127: 48
Please enter an integer between 48 and 127: 47
Please enter an integer between 48 and 127: 65

这是我的代码:

Please enter an integer between 32 and 127: 2
Please enter an integer between 32 and 127: 150
Please enter an integer between 32 and 127: 56
Please enter an integer between 32 and 127: 56
Please enter an integer between 56 and 127: 66
Please enter an integer between 32 and 127: 66
Please enter an integer between 66 and 127: 77

1 个答案:

答案 0 :(得分:3)

您调用enterNumber()函数5次,因此会接受5个接受的值:

  enterNumber(32,127);
  Please enter an integer between 32 and 127: 56 
  1st accepted number

  int min=enterNumber(32,127);
  Please enter an integer between 32 and 127: 56  // 2nd one
  2nd accepted number

  enterNumber(min,127);
  Please enter an integer between 56 and 127: 66
  3rd accepted answer.

  int max=enterNumber(enterNumber(32,127),127);    //called twice
  Please enter an integer between 32 and 127: 66
  Please enter an integer between 66 and 127: 77
  4th and 5 th accepted answer 

您可以通过删除第一个和第三个enternumber调用来更正您的逻辑。

   int enterNumber (int loLimit, int hiLimit){
   int min;
   int max;

   do {
      printf("Please enter an integer between %d and %d:\n", loLimit, hiLimit);
      scanf("%d", &min);
      }
   while (min<loLimit || min>hiLimit);
   return min;
  }

  int main(){
 // enterNumber(32,127); comment out this
  int min=enterNumber(32,127);

  // enterNumber(min,127);
   int max=enterNumber(min,127);
   int no=enterNumber(min,max);

}

首先它接受最小值,然后是最大值,最后在此范围之间输入一个。