随机数不在约束范围内

the*_*ser 1 java arrays histogram

所以,我确实做了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;}
Run Code Online (Sandbox Code Playgroud)

这是调用"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;}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 7

x介于0和1之间.

为了使e介于low和之间high,您需要:

e=(high-low)*x+low;
Run Code Online (Sandbox Code Playgroud)