为什么我的"While Loop"计算和打印出一个简单的3N + 1等式?

Sha*_*haz 0 java loops while-loop date-arithmetic system.out

所以我不得不写一个简单的代码来计算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");
    }

}
Run Code Online (Sandbox Code Playgroud)

Lee*_*Gup 5

这是错误的:if (N == N % 2 ) N%2返回1或0.你应该if (0 == N % 2 )用来检查奇数/偶数.