Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

java - Math.random()解释(Math.random() explanation)

This is a pretty simple Java (though probably applicable to all programming) question:

(这是一个非常简单的Java(虽然可能适用于所有编程)问题:)

Math.random() returns a number between zero and one.

(Math.random()返回一个介于0和1之间的数字。)

If I want to return an integer between zero and hundred, I would do:

(如果我想返回0到100之间的整数,我会这样做:)

(int) Math.floor(Math.random() * 101)

Between one and hundred, I would do:

(在一百到一百之间,我会做:)

(int) Math.ceil(Math.random() * 100)

But what if I wanted to get a number between three and five?

(但是,如果我想获得三到五之间的数字怎么办?)

Will it be like following statement:

(是否会像以下声明:)

(int) Math.random() * 5 + 3

I know about nextInt() in java.lang.util.Random .

(我知道java.lang.util.Random nextInt() 。)

But I want to learn how to do this with Math.random() .

(但我想学习如何使用Math.random()来做到这一点。)

  ask by switz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
int randomWithRange(int min, int max)
{
   int range = (max - min) + 1;     
   return (int)(Math.random() * range) + min;
}

Output of randomWithRange(2, 5) 10 times:

(randomWithRange(2, 5)输出10次:)

5
2
3
3
2
4
4
4
5
4

The bounds are inclusive, ie [2,5], and min must be less than max in the above example.

(边界是包容性的,即[2,5],并且在上面的例子中min必须小于max 。)

EDIT: If someone was going to try and be stupid and reverse min and max , you could change the code to:

(编辑:如果有人要尝试愚蠢并反转minmax ,您可以将代码更改为:)

int randomWithRange(int min, int max)
{
   int range = Math.abs(max - min) + 1;     
   return (int)(Math.random() * range) + (min <= max ? min : max);
}

EDIT2: For your question about double s, it's just:

(编辑2:关于double s的问题,它只是:)

double randomWithRange(double min, double max)
{
   double range = (max - min);     
   return (Math.random() * range) + min;
}

And again if you want to idiot-proof it it's just:

(再次,如果你想要愚蠢的证明它只是:)

double randomWithRange(double min, double max)
{
   double range = Math.abs(max - min);     
   return (Math.random() * range) + (min <= max ? min : max);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...