用Java获取随机数[重复]

本文介绍了如何在Java中生成1到50之间的随机数,包括使用Math.random()方法和Random类的方法,并提供了详细的解释和示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:Getting random numbers in Java [duplicate]

Possible Duplicate: 可能重复:
Java: generating random number in a range Java:生成一定范围内的随机数

I would like to get a random value between 1 to 50 in Java. 我想在Java中获得1到50之间的随机值。

How may I do that with the help of Math.random(); 我该如何在Math.random();的帮助下做到这一点Math.random(); ?

How do I bound the values that Math.random() returns? 如何绑定Math.random()返回的值?


#1楼

参考:https://stackoom.com/question/Ohf3/用Java获取随机数-重复


#2楼

int max = 50;
int min = 1;

1. Using Math.random() 1.使用Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double 如果是int,这将为您提供1到50的值;如果是double,这将为您提供1.0(含)到50.0(不包括)的值

Why? 为什么?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). random()方法返回一个介于0.0和0.9之间的随机数...,将它乘以50,所以上限将变为0.0到49.999 ...,当您添加1时,它变为1.0到50.999 ...,现在是截断时到int,您得到1到50。(感谢@rup的注释)。 leepoint's awesome write-up on both the approaches. leepoint关于这两种方法的文章都很棒。

2. Using Random class in Java. 2.在Java中使用Random类。

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49. 这将给出从0到49的值。

For 1 to 50: rand.nextInt((max - min) + 1) + min; 对于1到50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness. 一些Java Random Awesomeness的来源


#3楼

The first solution is to use the java.util.Random class: 第一种解决方案是使用java.util.Random类:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random() : 另一个解决方案是使用Math.random()

double random = Math.random() * 49 + 1;

or 要么

int random = (int)(Math.random() * 50 + 1);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值