随机数错误

Error with random number

这段代码有问题,不确定是什么,我正在尝试生成一个介于 0.8 和 1.2 之间的随机数,然后可以将其用于乘以使用该程序生成的分支的长度。

import java.awt.*;
import javax.swing.*;
import java.util.Random;


public class OneFractalTree extends JApplet {

final double ONE_DEGREE   = Math.PI/180;  
final double BRANCHANGLE  = ONE_DEGREE*30; 
final double SHRINKFACTOR = .65;           
final int    START_LENGTH = 75;            

//Draws branches
public void drawbranch( Graphics g, 
                        double   startx, //coordinates of branch start
                        double   starty, 
                        double   length, //length of branch
                        double   angle   ) //angle of branch
{
    double endx = startx + Math.sin(angle) * length; //Calculates the end coordinates of the branch
    double endy = starty + Math.cos(angle) * length;

    /** 
     * The loop draws the branches and continues until the length becomes too small 
     * i.e. when length is less than 1, length becomes smaller by shrinkfacter every iteration)
     */
    if( 1 < length ) {      

         Random rand = new Random();
         int randomNum = rand.nextInt((12 - 8) + 1) + 1;
         double randomNumdouble = randomNum / 10;



        g.setColor( length < 5 ? Color.green : Color.black ); //Sets color according to length
        g.drawLine( (int)startx, (int)starty, (int)endx, (int)endy ); //Coordinates to draw line
        drawbranch( g, endx, endy, (length * SHRINKFACTOR) * randomNumdouble, angle - BRANCHANGLE ); //1st branch creation
        drawbranch( g, endx, endy, (length * SHRINKFACTOR) * randomNumdouble, angle + BRANCHANGLE ); //2nd branch creation
        drawbranch( g, endx, endy, (length * SHRINKFACTOR) * randomNumdouble, angle); //3rd branch creation
    }
}


public void paint( Graphics g ) {
    Rectangle r = getBounds(); //Finds height of applet viewer
    drawbranch( g, r.width/2, r.height, START_LENGTH, Math.PI );     //Calls method to draw branch
}

}

正确的公式是

Random.nextDouble() * (max - min) + min;

但要修复您的代码:

int randomNum = rand.nextInt((12 - 8) + 1) + 1;
double randomNumdouble = randomNum / 10.0; // 10 will be interpreted as an `int`, whereas 10.0 will be a `double`

randomNum/10是整数运算,尝试使用/10.0/10f来使用浮点运算。

/10 的问题在于它会将值下限到最接近的整数

您声明了 int randomNum,它是一个整数。所以 randomNum / 10 正在生成一个整数值,因为 randomNum10 都是整数类型。最后,您将 int 类型结果分配给 double 类型变量,而无需任何类型转换。 做到 double randomNumdouble = randomNum / 10.0