退出带有负整数的 while 循环 [英] exiting a while loop with a negative integer
问题描述
我想在用户输入任意大小的负数时退出 while()
.当用户输入负数时,在循环开始时我需要什么样的条件才能让循环退出?
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 when the user enters a negative number?
推荐答案
那么,什么是负数?它是一个小于零的数字(称为 x
),或者象征性地,x <0
.如果 x
小于零,则为真.如果不是,那就是假的.
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;
}
...
}
但我更喜欢在 while
循环本身中使用与该条件相反的条件:
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.
这篇关于退出带有负整数的 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!