Java产生特定范围内的随机整数
来源:互联网 发布:网络协议软件 编辑:程序博客网 时间:2024/04/29 22:42
http://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java
One standard pattern for accomplishing this is:
Min + (int)(Math.random() * ((Max - Min) + 1))
The Java Math library function Math.random() generates a double value in the range [0,1). Notice this range does not include the 1.
In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.
Math.random() * ( Max - Min )
This returns a value in the range [0,Max-Min]
.
For example, if you want [5,10]
, you need to cover five integer values so you use
Math.random() * 5
This would return a value in the range [0,5]
.
Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.
Min + (Math.random() * (Max - Min))
You now will get a value in the range [Min,Max)
. Following our example, that means [5,10]
:
5 + (Math.random() * (10 - 5))
But, this is still doesn't include Max
and you are getting a double value. In order to get the Max
value included, you need to add 1 to your range parameter (Max - Min)
and then truncate the decimal part by casting to an int. This is accomplished via:
Min + (int)(Math.random() * ((Max - Min) + 1))
And there you have it. A random integer value in the range [Min,Max]
, or per the example [5,10]
:
5 + (int)(Math.random() * ((10 - 5) + 1))
- Java产生特定范围内的随机整数
- java 随机生成18到25范围内的整数
- java 随机生成18到25范围内的整数
- 【Java】产生1-10的随机整数
- JS math.random随机数,产生指定范围内的随机整数的代码
- C语言基础 产生一个0到n-1范围内的随机整数
- java7: 使用随进函数产生特定范围的随机整数及随机字符
- 生成某个范围内的随机整数公式
- 如何获取一个范围内的随机整数
- js生成指定范围内的随机整数
- js取一定范围内的随机整数
- 编写一个产生1000个1到10范围内的随机整数,统计各数字出现的次数
- Java产生任意范围内的随机字符,内部多种方法进行调用
- 《Java编程技巧1001条》359条:建立指定范围内的随机整数
- 产生指定范围内指定长度的随机字符串
- 产生整数随机数在两个数的范围内
- [转]mysql 随机函数生成某个范围内的整数
- mysql 随机函数生成某个范围内的整数
- php操作MySQL数据库中语句基础应用
- 某博客提供的代码与工具(Java)
- 数据库设计中的三大范式概念
- Unity3D入门(三):创建对象
- cxgrid不可以修改用union all语句组合的表
- Java产生特定范围内的随机整数
- UVa 10507 - Waking up brain
- Codeforces Round #206 (Div. 2) C - Vasya and Robot
- oracle动态性能表
- oracle创建表空间
- oracle用户权限,系统权限
- Unity3D入门(四):摄像机控制
- shell script 脚本传递参数的方法
- UITableView执行顺序及Segue必须要实现的方法