【问题标题】:Random number isn't within contraints随机数不在约束范围内
【发布时间】:2015-06-21 11:53:54
【问题描述】:

所以,我确实重新做了e=(high-low)*x+low,但是,当我尝试使用它时,它只是返回了一个 outOfBounds 异常。当我没有将它转换为 int 时,它可以工作,但是我需要它返回一个整数,以便数组工作。

public static int randomInt(int low, int high)
    {double e;
    double x=Math.random();
        e=(high-low)*x+low;
    return (int)e;}

这里是调用“randomInt”方法的方法

public static int[] randomIntArray(int n)//generates an array of random numbers based on an upper and lower bound
    {int[] a=new int[n];
    for(int i=0;i<a.length;i++)
        {a[i]=randomInt(-5,15);}//"-5&15 are the lower and upper bounds of the random number array
    return a;}

【问题讨论】:

  • 为什么不使用java.Util.Random#nextInt()
  • 这不应该抛出 OutOfBoundsException。
  • 事实证明,OutOfBoundsException 不是来自我必须打印的打印方法。

标签: java arrays histogram


【解决方案1】:

x 介于 0 和 1 之间。

为了使 e 介于 lowhigh 之间,您需要:

e=(high-low)*x+low;

【讨论】:

    【解决方案2】:

    查看this

    public static int randInt(int min, int max) {
    
        Random rand = new Random();
    
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;
    
        return randomNum;
    }
    

    【讨论】:

      【解决方案3】:

      改用return (int) (Math.random()*(high-low)+low); 作为你的函数体。

      【讨论】:

      • 当我使用它时,我只是得到一个越界异常
      猜你喜欢
      • 2022-11-03
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 2018-06-22
      相关资源
      最近更新 更多