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

查看:172
本文介绍了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.

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

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)

但如果我想获得三到五之间的数字怎么办?它是否如下声明:

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中了解 nextInt()。 lang.util.Random 。但我想学习如何使用 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

边界是包含的,即[2,5], min 必须小于 max 在上面的示例中。

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

编辑:如果有人打算尝试愚蠢并逆转 min max ,您可以将代码更改为:

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

EDIT2:有关<$ c的问题$ c> 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);
}

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

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