【问题标题】:Having trouble with a while loop that gets a certain series of numbers from an input从输入中获取特定系列数字的 while 循环遇到问题
【发布时间】:2015-01-18 08:53:53
【问题描述】:

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

我正在解决的问题是:http://i.imgur.com/VzuPtZJ.png

使用我目前拥有的代码(如下所示),如果我输入 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);
    }
}

【问题讨论】:

    标签: java if-statement random input while-loop


    【解决方案1】:

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

    改变这一行

    (x % 12 == 0)
    

    (x % 2 == 0)
    

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

    【讨论】:

    • 不敢相信我看错了,谢谢!虽然当我改变它时,当我执行代码并输入 12 时,程序冻结,我没有得到任何输出,光标符号只是在下一行闪烁。
    • 查看我的编辑。你的时间是问题所在。它应该在等于 1 时停止。
    • 谢谢!提到确切的问题,不要误解我复制了你的答案,因为我是从最后 10 分钟开始这样做的!
    【解决方案2】:

    这是您要查找的代码:-

    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 % 2 == 0)
                    x = x / 2;
                else
                    x = 3*x + 1;
    
               System.out.print(x+" ");
        max++;    
        }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多