【问题标题】:Random method always returning minimum value in for-loop?随机方法总是在for循环中返回最小值?
【发布时间】:2022-01-15 06:51:41
【问题描述】:

我正在使用我创建的随机方法,而不是 java.util.Random 类。该类称为“Randomizer”,这是其中的代码:

public class Randomizer{
  public static int nextInt(){
    return (int)Math.random() * 10 + 1;
  }

  public static int nextInt(int min, int max){
    return (int)Math.random() * (max - min + 1) + min;
  }
}

这段代码应该可以正常工作,但是当我在 for 循环中调用它时(如下所示),它总是返回最小值。

public class Main
{
    public static void main(String[] args)
    {
        System.out.println("Results of Randomizer.nextInt()");
        for (int i = 0; i < 10; i++)
        {
          System.out.println(Randomizer.nextInt());
        }
        int min = 5;
        int max = 10;
        System.out.println("\nResults of Randomizer.nextInt(5, 10)");
        for (int i = 0; i < 10; i++)
        {
          System.out.println(Randomizer.nextInt(min, max));
        }
    }
}

此代码返回以下内容:

Results of Randomizer.nextInt()
1
1
1
1
1
1
1
1
1
1

Results of Randomizer.nextInt(5, 10)
5
5
5
5
5
5
5
5
5
5

我认为这个错误与 Randomizer 中的方法是静态的这一事实有关,但我无法想象如何解决这个问题。任何帮助将不胜感激!

【问题讨论】:

    标签: java for-loop random


    【解决方案1】:

    Math.random() 返回[0, 1) 范围内的浮点数(双精度)。当您将该双精度转换为整数时,它每次都会截断为 0。

    要解决您的问题,您需要在尝试完成所有数学运算后进行强制转换。所以,它应该是这样的:

    public class Randomizer{
      public static int nextInt(){
        return (int)(Math.random() * 10 + 1);
      }
      public static int nextInt(int min, int max){
        return (int)(Math.random() * (max - min + 1) + min);
      }
    }
    

    注意要转换为整数的表达式周围的额外括号。

    【讨论】:

      猜你喜欢
      • 2012-08-28
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2012-10-26
      • 1970-01-01
      相关资源
      最近更新 更多