以负整数退出 while 循环
当用户输入任意大小的负数时,我想退出 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那么,什么是负数呢?它是一个小于零的数字(称为
x
),或者象征性地,x
x
x
。 0 。如果 x 小于零,则这是真的。如果不是,那就是假的。您可以无限循环并在满足此条件时中断:
但我更喜欢在 while 循环本身中使用与该条件相反的条件:
当条件为 true 时,循环将继续。当它为假时(并且您的原始条件为真,因为这两个条件相反),循环就会中断。
Well, what is a negative number? It's a number (call it
x
) that is less than zero, or symbolically,x < 0
. Ifx
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:
But I prefer to just use the opposite of that condition in the
while
loop itself: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.
使用
if
条件判断数字是否小于 0。如果是,只需在其中使用break
语句,这将使您跳出循环。 从 MSDN 了解有关 break 语句的详细信息。Use an
if
condition to know the number is less than 0 or not. And if yes, just usebreak
statement inside it, which will bring you out of the loop. Learn more about break statement from MSDN.编辑:抱歉,我的错误:“i”没有正确声明:)现在应该可以使用了
edit: sorry, my mistake: 'i' wasn't declared properly :) now it should be fine to use
不要将变量定义为无符号变量。正如其他答案中所建议的,使用 if 语句并用 if 语句中断。
例子:
Do not define your variable as unsigned variable. As suggested in other answers use if statement and break with if statement.
example: