简体   繁体   English

无法使用||退出循环 操作者

[英]Cannot exit the loop using || operator

Could you explain me please why my code "hangs" when I use short-circuit OR in a loop? 您能否解释一下为什么在短路或循环中我的代码“挂起”?

I have written a code to calculate the greatest common factor of two integers: 我已经编写了一个代码来计算两个整数的最大公因数:

  int a = 9; int b = 6; while (a != 0 || b != 0) //here is the problem { if (a >= b) { a = a - b; } else b = b - a; } if (a == 0) System.out.println(b); else System.out.println(a); 

When I use || 当我使用||时 operator, what seems logical to me in my case, the running of my programme never stops. 运算符,对我来说,逻辑上来说,程序的运行永不停止。 However, when I use && operator, what seems not logical to me, it works perfectly. 但是,当我使用&&运算符时,对我来说似乎不合逻辑的操作非常完美。 Can you explain me please why I cannot exit the loop using the || 您能解释一下我为什么不能使用||退出循环吗? operator? 运营商?

Let's examine the output step by step (each step corresponds to one loop): 让我们逐步检查输出(每个步骤对应一个循环):

step 1: 第1步:

a >= b is true so a is now equal to 3

step 2: 第2步:

b >= a is true so b is now equal to 3

step 3: 步骤3:

a >= b is true so a is now equal to 0

Let's stop here. 让我们在这里停止。 The while loop is going to continue running while either a OR b are not equal to 0. In all subsequent loops b will be set to 3 - 0 and the values will never change - it will run infinitely. 当OR或b不等于0时,while循环将继续运行。在所有后续循环中,b都将设置为3-0,并且值永远不会改变-它将无限运行。 If your goal is to stop the loop when 1 value reaches 0 you need and && statement. 如果您的目标是在1值达到0时停止循环,则需要使用&&语句。

By using AND, you're saying "if one is zero, exit the loop." 通过使用AND,您的意思是“如果一个为零,则退出循环。” If you use OR, you're saying "if both are zero, exit the loop". 如果使用OR,则表示“如果两者均为零,则退出循环”。 It's opposite what you think it is, and that's why you might be confused. 这与您的想法相反,这就是为什么您可能会感到困惑的原因。 When you negate boolean operators like this, AND becomes OR and vice versa. 当您像这样取消布尔运算符时,AND变为OR,反之亦然。 You can learn more about this from DeMorgan's Laws. 您可以从DeMorgan的定律中了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM