Math.random() 解释 [英] Math.random() explanation

查看:55
本文介绍了Math.random() 解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

如果我想返回一个零到一百之间的整数,我会这样做:

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

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

在一到一百之间,我会这样做:

Between one and hundred, I would do:

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

但是如果我想得到一个介于 3 和 5 之间的数字怎么办?会不会像下面的语句:

But what if I wanted to get a number between three and five? Will it be like following statement:

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

我知道 java.lang.util.Random 中的 nextInt().但我想学习如何使用 Math.random() 做到这一点.

I know about nextInt() in java.lang.util.Random. But I want to learn how to do this with Math.random().

推荐答案

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

randomWithRange(2, 5) 输出 10 次:

5
2
3
3
2
4
4
4
5
4

bounds are inclusive,即[2,5],上面例子中min必须小于max.

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

如果有人试图变得愚蠢并反转minmax,您可以将代码更改为:

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

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

对于您关于 double 的问题,它只是:

For your question about doubles, it's just:

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);
}

这篇关于Math.random() 解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆