生成两个数字之间的数字&四舍五入

时间:2015-02-13 20:21:19

标签: java

我想创建一个函数,返回“10 - 20”之间的双精度,我将在其他地方使用百分比;

我需要截断双倍因此它不再是14.4938而是14;如果有可能,我想使用Math.floor / round / ceil来解决这个问题,因为我想解决我的问题。

我已经尝试了几种方法,我已经解决了这个问题,使用Math.round这是有效的;但是获得10比其他数字的机会要低,因为据我所知,它只能在10-10.49999之间产生,相比之下,11可能是10.5-11.49。

也许如果我将Math.random()乘以1.09,并使用Math.ceil,我可以得到20.9的最大值,它将生成20,但这似乎是错误的。

        ranNum = (((Math.random() * 10) + 10));
        return Math.round((ranNum));

3 个答案:

答案 0 :(得分:0)

你可以做到

Math.floor(10 + Math.random() * 11)

如果你真的想用Math.random()生成一个双

答案 1 :(得分:0)

您可以使用Random类生成介于0和指定数字(不包括)之间的数字。将此与一些逻辑结合使用:

int low = 10;
int high = 20;
Random rand = new Random();
double randNum = rand.nextDouble(high-low + 1) + (double)low //returns number between 10 (inclusive) and 21 (exclusive) -- up to 20.99
return Math.floor(randNum); //makes sure number is between 10 and 20

答案 2 :(得分:0)

Random random = new Random();
int i = random.nextInt((max - min) + 1) + min;