简体   繁体   English

为什么我的“ While Loop”不计算并打印出简单的3N + 1方程?

[英]Why isn't my “While Loop” computing and printing out a simple 3N+1 equation?

So I had to write a simple code that would compute the 3N+1 equation; 因此,我不得不编写一个简单的代码来计算3N + 1方程; where N is an integer user types in and if it is a positive integer than N = N / 2 and if negative integer than N = N * 3 + 1. 其中N是用户输入的整数,如果它是N的正整数,则N = N / 2,如果是N的负整数,则N = N * 3 + 1。

However from what I can understand, my code doesn't work after the first while loop and hence prints nothing. 但是据我了解,我的代码在第一个while循环后无法正常工作,因此什么也不打印。 What am I doing wrong? 我究竟做错了什么? New to programming and still learning so I appreciate your help :) 编程和学习的新手,非常感谢您的帮助:)

Code: 码:

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");
    }

}

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

问题是您的if (N == N % 2) ,您可能只想检查if (N >= 0)因为您确实声明要检查if it is a positive integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM