当我为if语句输出大括号时,代码输出是无限循环,当我删除大括号时,它正常工作。
这是代码:
int gcd = 1;
int k = 2;
while (k <= number1 && k <= number2)
{
System.out.println("this is k " + k);
System.out.println("this is gcd " + gcd);
if(number1 % k == 0 && number2 % k == 0)
{
gcd = k;
k++;
System.out.println("this is k " + k);
System.out.println("this is gcd " + gcd);
}
}
答案 0 :(得分:1)
原因是 k 值从不 更新如果您将其放在if语句中。删除大括号后,代码将变为此
if(number1 % k == 0 && number2 % k == 0)
gcd = k;
k++;
System.out.println("this is k " + k);
System.out.println("this is gcd " + gcd);
if循环中唯一的一行是gcd=k
行。
这意味着每次进行while循环时k值总是在增加。
如果你把它放在if语句中,k可能永远不会进入因为if语句的限制因此它永远不会增加所以它总是&lt; = number1和&lt; = number2。在那里,你有一个无限循环。
答案 1 :(得分:0)
原因是因为您添加大括号的位置导致k
仅在if
语句求值为true
时递增。因此,如果if
语句不为真,k
不会递增,while
循环将永远继续,因为while
循环条件永远不会改变。
int gcd = 1;
int k = 2;
while (k <= number1 && k <= number2)
{
System.out.println("this is k " + k);
System.out.println("this is gcd " + gcd);
if(number1 % k == 0 && number2 % k == 0)
{
gcd = k;
k++; // THIS needs to be outside the if statement
System.out.println("this is k " + k);
System.out.println("this is gcd " + gcd);
}
}
相反,你应该这样:
int gcd = 1;
int k = 2;
while (k <= number1 && k <= number2)
{
System.out.println("this is k " + k);
System.out.println("this is gcd " + gcd);
if(number1 % k == 0 && number2 % k == 0)
{
gcd = k;
}
k++;
System.out.println("this is k " + k);
System.out.println("this is gcd " + gcd);
}