所以我必须编写一个简单的代码来计算 3N+1 方程;其中 N 是用户输入的整数,如果它是正整数,则 N = N / 2,如果是负整数,则 N = N * 3 + 1。
但是据我所知,我的代码在第一个 while 循环后不起作用,因此什么也不打印。我究竟做错了什么?编程新手,仍在学习,因此感谢您的帮助 :)
代码:
import java.util.Scanner;
public class ThreeNplusOneProgram {
public static void main(String[] args) {
int N; Scanner input = new Scanner(System.in); int counter;
System.out.println("Please Enter an integer: ");
N = input.nextInt();
while ( N <= 0 ) {
System.out.println("ERROR: Please Enter an integer greater than zero: ");
N = input.nextInt();
}
//So far we know that N is great than Zero
System.out.println(N);
counter = 1;
while ( N != 1 ) {
if (N == N % 2 )
N = N / 2;
else N = N * 3 + 1;
counter = counter + 1;
}
System.out.println("There were" + counter + "terms in the sequence");
}
}