我必须在Java中编写一个Hailstone Sequence代码,例如,它应该像这样:
10 5 16 8 4 2 1 4 2 1
我的想法是这样的:
10 5 16 8 4 2 1
该如何解决?
这是我的代码:
static int counter;
static int HailstoneNumbers(int Number)
{
System.out.print(Number+ " ");
if (Number == 1 && counter == 0) {
return counter;
}
else if (Number == 1 && counter != 0) {
counter++;
return counter;
}
else if (Number % 2 == 0) {
counter++;
HailstoneNumbers(Number / 2);
}
else if (Number % 2 != 0) {
counter++;
HailstoneNumbers(3 * Number + 1);
}
return counter;
}
public static void main(String[] args)
{
int Number;
KeyboardReader reader = new KeyboardReader();
System.out.println("What is your intial value? ");
Number = reader.readInt();
int x;
x = HailstoneNumbers(Number);
System.out.println();
System.out.println("Number of Steps: " +x);
}
}
答案 0 :(得分:0)
您的代码明确地表示在到达数字1时停止序列。也许您的意思是根据计数器的值,行为会有所不同,但尚不清楚为什么应该< em>不要停在第一个1,但应该停在第二个(因为counter
都不是0)。