這個程序是針對Java的。它意味着要做Collatz猜想。在我的明代碼應該工作,但是當我輸入7它打印出一堆22的我認爲它與java保存ints問題。java不能正確保存整數
import java.util.*;
//If n is even, divide it by 2 to get n/2. If n is odd, multiply it by 3 . and add 1
public class infNum {
private int num;
private int n;
private String comma = ", ";
public void start() {
System.out.println("enter a number");
Scanner keyboard = new Scanner (System.in);
int n = keyboard.nextInt();
num = n;
}
public void testEvenOdd() {
if((num % 2) == 0) {
ifEven(num);
} else {
ifOdd(num);
}
}
public void ifEven(int num) {
if(num == 1) {
return;
} else {
num = num/2;
System.out.print(num + comma);
testEvenOdd();
}
}
public void ifOdd(int num) {
if(num == 1) {
return;
} else {
num = (num * 3) +1;
System.out.print(num + comma);
testEvenOdd();
}
}
}
好吧,'7'是一個奇數。 「7 * 3」是21,「21 + 1」是** 22。看起來你的程序完全符合你的要求。 –
這是怎麼回事?起始方法在哪裏,如果是開始方法,其他方法都不會被調用? –
這更多的是你的'testEvenOdd'方法檢查'num'實例變量的問題,而你的其他方法永遠不會更新它。目前他們只更新他們自己的參數,當方法結束時,參數超出範圍。 – azurefrog