java - 使用 while 循环从输入获取特定系列的数字时遇到问题

标签 java if-statement random input while-loop

如果 % 12 == 0,我会尝试将输入减半,但如果不是,则将其乘以 3,然后在总和上加 1。

我正在解决的问题是:/image/lOxQs.png

enter image description here

使用我当前的代码(如下),如果我输入 12,就像在问题中一样,我从 6 开始,但结果开始出错,然后在数百万和负数百万等值上出现疯狂的错误。

import java.util.*;
public class sheet12t3
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int aNumber = Integer.parseInt(in.nextLine());
        hailstone(aNumber);
    }

    public static void hailstone(int x)
    {
        int count = 1;
        int max = 0;
        String results = "Hailstone series for the number " + x + " is ";
        while (x >= 1)
        {
            if (x % 12 == 0)
                x = x / 2;
            else
                x = 3 * x + 1;

            count++;

            results += + x + ", ";

            if (x > max)
                max = x;
        }
        results += "a total of " + count + " numbers in this sequence with a maximum value of " + max;
        System.out.print(results);
    }
}

最佳答案

问题说如果数字是偶数则除以二。但只有当它能被 12 整除时,你才能除以 2。

更改此行

(x % 12 == 0)

(x % 2 == 0)

并将 while (x >= 1) 更改为 while (x > 1)

关于java - 使用 while 循环从输入获取特定系列的数字时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27040554/

相关文章:

c++ - 将类内的随机数 boost 为静态成员

java - native 创建的 Java 对象是否需要同步才能 Access ?

javascript - 根据父 div id 加载 Javascript 文件

r - R if语句中的多个条件

PHP 等效于 javascript Math.random()

C++生成随机数

java - 独立 Java 应用程序是否需要私有(private)?

java - spring中@ModelAttribute、model.addAttribute有什么区别?

java - Flyway 可以与非托管数据库对象共存吗?

java - "blocks[i][j].isColorBox() ? pieceColor : backgroundColor"的长版本是什么?