以负整数退出 while 循环

发布于 2024-12-09 18:34:17 字数 78 浏览 0 评论 0原文

当用户输入任意大小的负数时,我想退出 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

双马尾 2024-12-16 18:34:17

那么,什么是负数呢?它是一个小于零的数字(称为x),或者象征性地,x x x。 0 。如果 x 小于零,则这是真的。如果不是,那就是假的。

您可以无限循环并在满足此条件时中断:

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

  ...
}

但我更喜欢在 while 循环本身中使用与该条件相反的条件:

 while (x >= 0) {
   ...

当条件为 true 时,循环将继续。当它为假时(并且您的原始条件为真,因为这两个条件相反),循环就会中断。

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.

伴梦长久 2024-12-16 18:34:17

使用 if 条件判断数字是否小于 0。如果是,只需在其中使用 break 语句,这将使您跳出循环。 从 MSDN 了解有关 break 语句的详细信息。

Use an if condition to know the number is less than 0 or not. And if yes, just use break statement inside it, which will bring you out of the loop. Learn more about break statement from MSDN.

雪花飘飘的天空 2024-12-16 18:34:17
int i = -1;
do
{
    i = magic_user_input();
    //simple enough? get a decent programming book to get the hang of loops
}
while(i > -1)

编辑:抱歉,我的错误:“i”没有正确声明:)现在应该可以使用了

int i = -1;
do
{
    i = magic_user_input();
    //simple enough? get a decent programming book to get the hang of loops
}
while(i > -1)

edit: sorry, my mistake: 'i' wasn't declared properly :) now it should be fine to use

揽清风入怀 2024-12-16 18:34:17

不要将变量定义为无符号变量。正如其他答案中所建议的,使用 if 语句并用 if 语句中断。

例子:

int main(void)
{
 int i;
 while(1){
 /*here write an statement to get and store value in i*/ 
  if(i<0)
  {
    break;
  }
 /*other statements*/
  return(0);
  }
 } 

Do not define your variable as unsigned variable. As suggested in other answers use if statement and break with if statement.

example:

int main(void)
{
 int i;
 while(1){
 /*here write an statement to get and store value in i*/ 
  if(i<0)
  {
    break;
  }
 /*other statements*/
  return(0);
  }
 } 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文