exiting a while loop with a negative integer

前端 未结 4 478
情话喂你
情话喂你 2021-01-27 13:15

I want to exit a while() when the user enters a negative number of any size. What kind of condition would I need at the start of the loop to get the loop to exit w

4条回答
  •  渐次进展
    2021-01-27 14:02

    Well, what is a negative number? It's a number (call it x) that is less than zero, or symbolically, x < 0. If x is less than zero, then this is true. If not, then it is false.

    You can loop endlessly and break when this condition is met:

    while (1) {
      if (x < 0) {
        break;
      }
    
      ...
    }
    

    But I prefer to just use the opposite of that condition in the while loop itself:

     while (x >= 0) {
       ...
    

    While the condition is true, then the loop continues. When it is false (and your original condition is true, as these two are opposite), the loop breaks.

提交回复
热议问题