这段代码有问题而不确定是什么,我试图在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
}
}
答案 0 :(得分:0)
正确的公式是
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`
答案 1 :(得分:0)
randomNum/10
是整数运算,尝试使用/10.0
或/10f
来使用浮点运算。
/10
的问题在于它会将值置于最接近的整数
答案 2 :(得分:0)
您声明int randomNum
这是一个整数。因此randomNum / 10
生成一个整数值,因为randomNum
和10
都是整数类型。最后,您将int
类型结果分配给double
类型变量,而不进行任何类型转换。
设为double randomNumdouble = randomNum / 10.0