【发布时间】:2015-01-18 08:53:53
【问题描述】:
如果 % 12 == 0,我会尝试将输入减半,但如果不是,则将其乘以 3 并在总和上加 1。
我正在解决的问题是:http://i.imgur.com/VzuPtZJ.png
使用我目前拥有的代码(如下所示),如果我输入 12,就像在问题中我从 6 开始一样,但是结果开始出错,然后它们在数百万的值和负数百万等。
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x >= 1)
{
if (x % 12 == 0)
x = x / 2;
else
x = 3 * x + 1;
count++;
results += + x + ", ";
if (x > max)
max = x;
}
results += "a total of " + count + " numbers in this sequence with a maximum value of " + max;
System.out.print(results);
}
}
【问题讨论】:
标签: java if-statement random input while-loop