如何将int的值更改为循环方程的结果

  • 本文关键字:循环 方程 结果 int java
  • 更新时间 :
  • 英文 :


Java新手。我必须创建一个冰雹序列,经过5个小时的头痛,我完全迷路了。基本上,我需要获取用户的数字,并通过一个根据数字是偶数还是奇数而变化的等式来运行它。然后我需要获取结果并再次运行它,直到最终结果=1。

我想不通的是如何让程序使用上一次计算的结果来进行循环中的下一次计算。

示例:

int x = readInt("Enter a number: ");
int xEven = (x/2);
int xOdd = (x*3+1);
int counter = 0;

public void run()
{
while(x != 1)
{
if(x % 2 == 0)
{
println(x + " is even, so I take half: " + xEven);
}
else
{
println(x + " is odd, so i make 3x + 1: " + xOdd);
}
counter++;
}
println("The process took " + counter + " steps to reach 1.");
}

结果应该是这样的:

Enter a number: 17
17 is odd, so I make 3x + 1: 52
52 is even, so I take half: 26
26 is even, so I take half: 13
13 is odd, so I make 3x + 1: 40
40 is even, so I take half: 20
20 is even, so I take half: 10
10 is even, so I take half: 5
5 is odd, so I make 3x + 1: 16
16 is even, so I take half: 8
8 is even, so I take half: 4
4 is even, so I take half: 2
2 is even, so I take half: 1
The process took 12 steps to reach 1.

当我运行我的代码时,它只会永远重复第一个输入,而不会循环,所以它看起来像这样:

17 is odd, so I make 3x + 1: 52
17 is odd, so I make 3x + 1: 52
17 is odd, so I make 3x + 1: 52
17 is odd, so I make 3x + 1: 52
17 is odd, so I make 3x + 1: 52
17 is odd, so I make 3x + 1: 52
etc...
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number: ");
int x = scan.nextInt();
int steps = 0;
while (x != 1) {
if (x % 2 == 0)
System.out.format("%d is even, so I take half: %dn", x, x /= 2);
else
System.out.format("%d is odd, so I make 3x + 1: %dn", x, x = 3 * x + 1);
steps++;
}
System.out.format("The process took %d steps to reach 1.", steps);
}

您需要将新值分配给变量x。例如,在打印后立即执行x = xEven;x = xOdd。此外,您还需要在while循环中移动xEvenxOdd的计算。

附言:有几种可能的方法来减少你的代码。

如果您需要更多的解释,请随时询问。

您就快到了。只需通过注释进行以下更改即可。但首先,删除您以前声明的xEvenxOdd

while (x != 1) {
if (x % 2 == 0) {
x = x / 2;                   //add
int xEven = x;               //add
System.out.println(
x + " is even, so I take half: " + xEven);
} else {
x = x * 3 + 1;               //add
int xOdd = x;                //add
System.out.println(
x + " is odd, so i make 3x + 1: " + xOdd);
}
counter++;
}
System.out.println(
"The process took " + counter + " steps to reach 1.");

我还在println中添加了System.out。如果你使用的是不同的软件包,那么你可能不需要更改它。

最新更新