该程序应该在1处停止循环,但是如果有多个if,它将继续循环。我可以使用if-else完成练习,但是在这里我无法跟踪和理解多个ifs和if-else之间的区别。
我是新来的,所以在此先感谢大家的帮助。
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a starting value: ");
int input = keyboard.nextInt();
System.out.print(input + ",");
System.out.print(" ");
while (input != 1) {
if (input % 2 == 0) {
input = input / 2;
System.out.print(input + ",");
System.out.print(" ");
}
if (input % 2 == 1) { // replace with else
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
}
keyboard.close();
}
预期:程序应在1(检查时)停止
Actual::它继续无限循环:4 2 1 4 2 1 ....
答案 0 :(得分:7)
由于起始值为4
,因此第一个if语句将其减小为2
。在循环的下一次迭代中,第一个if语句将其减少为1
,但是第二个if语句看到它是一个奇数并将其乘以3
并加{{1} }。
要解决此问题,您的第二个if语句需要替换为1
,因为只有两种可能的情况:
else
这样可以确保如果执行第一个if语句,则不会执行第二个if语句。
答案 1 :(得分:1)
当输入进入值为2的while循环时,如果第一个if和离开块时其值为1,则进入第一个。然后,如果if的值被设置为4,则进入2。值4 2 1 ...
答案 2 :(得分:1)
考虑输入为2时的情况
case 1. with 2 ifs first if will make the input 1 and 2nd if will be executed and will make it again 4.
case 2 . with if else , once the input becomes 1 after first if it will come out of loop , and hence the result.
答案 3 :(得分:1)
不是答案 ,但与Collatz序列相关。
(输入第一个if
时发生的错误更改了input
,导致输入
如果没有if
,则第二个else
。)
1 -> 1
odd n -> 3n+1 (even!)
even n -> n/2
如您所见,奇数n的捷径可分为两个步骤:
odd n ->-> (3n+1)/2
对于数学研究,这是一个更好的顺序。
然后,您可以完全不用else
。
while (input != 1) {
if (input % 2 == 1) {
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
/*if (input % 2 == 0)*/ {
input /= 2;
System.out.print(input + ",");
System.out.print(" ");
}
}
答案 4 :(得分:1)
while循环将继续迭代,直到变量的值input为1。在您的示例示例中,当您输入input = 4时,将有无限次迭代(循环将根据条件无限执行)
在while循环之前,它会打印 4 (输入)
迭代1:输入为4。while循环时输入->如果为4%2 = 0,则输入1st并将输入重新分配给4/2 = 2->打印 2 ->不输入如果为2%2 = 0,则为第二
迭代2:输入为2。while循环时输入->如果为2%2 = 0,则输入1st,然后将输入重新分配为2/2 = 1。打印 1 ->如果现在作为输入= 1输入1%2 = 1,则输入2nd。 ->重新分配输入= 3 * 1 + 1 =4。打印4
然后将其再次统计为4。它将继续无限打印 4 2 1 4 2 1 4 2 1 ...
while (input != 1) {
//1st if
if (input % 2 == 0) {
input = input / 2;
System.out.print(input + ",");
System.out.print(" ");
}
//2nd if
if (input % 2 == 1) { // replace with else
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
}
Else语句仅在if条件失败时执行。当您用else语句替换第二个if条件时,程序将不会再次将输入值分配为4。因此,它将在 1 处停止,打印 4 2 1
答案 5 :(得分:1)
即使前一个条件在多个 if 语句中通过或失败,也会检查每个 if 条件。但是在 if-else 块的情况下,如果传递了任何一个,则跳过其他。
答案 6 :(得分:0)
尝试一下:
while (input != 1) {
if (input % 2 == 0) {
input = input / 2;
System.out.print(input + ",");
System.out.print(" ");
}
else { // replace with else
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
}
在您的代码中:
while (input != 1) {
if (input % 2 == 0) {
input = input / 2;
System.out.print(input + ",");
System.out.print(" ");
}
if (input % 2 == 1) { // replace with else
input = 3 * input + 1;
System.out.print(input + ",");
System.out.print(" ");
}
}
在您的代码中,如果输入为2,则input = input / 2;
该语句将输入1。接下来,input % 2 == 1
变为true时,它将使输入等于4(input = 3 * input + 1;
),并且循环不会结束。您应该改用else。甚至代码也被注释为// replace with else