Java随机数的生成
2022/8/29 1:25:13
本文主要是介绍Java随机数的生成,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Random类
生成一个[0,10)的随机整数
Random random = new Random();
int num1 = random.nextInt(10);
生成一个[0,10]范围的随机整数
[0,11) -> [0,10]
int num2 = random.nextInt(11);
生成一个[1,10]范围的随机整数
[0+1,10+1) -> [1,11) -> [1,10]
int num3 = random.nextInt(10) + 1;
Math.random()
它的作用是生成一个[0,1)的随机小数
生成一个[0,10)的随机小数
double类型的[0,10)
[0,1) -> [0,10)
double a_double = Math.random() * 10;
生成一个[0,10)的随机整数
int num1 = (int)a_double;
生成一个[0,10]范围的随机整数
强转为int时是向下取整 floor()
[0,10+0.5) -> [0,10.5) -> [0,10]
int num2 = (int) (a_double + 0.5);
或一步到位
int num3 = (int) (Math.random() * 10 + 0.5);
生成一个[1,11]范围的随机整数
[0+1.5,10+1.5) -> [1.5,11,5] 向下取整为 -> [1,11]
int num4 = (int) (Math.random() * 10 + 1.5);
测试代码
for (int i = 0; i < 1000; i++) {
a = (int) (Math.random() * 10 + 1.5);
if (a == 1) System.out.println(0);
if (a == 11) System.out.println(11);
}
这篇关于Java随机数的生成的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-0601-电商商品中心解密:仅凭SKU真的足够吗?
- 2024-05-01为什么公共事业机构会偏爱 TiDB :TiDB 数据库在某省妇幼健康管理系统的应用
- 2024-04-26敏捷开发:想要快速交付就必须舍弃产品质量?
- 2024-04-26静态代码分析的这些好处,我竟然都不知道?
- 2024-04-26你在测试金字塔的哪一层?(下)
- 2024-04-26快刀斩乱麻,DevOps让代码评审也自动起来
- 2024-04-262024年最好用的10款ER图神器!
- 2024-04-2203-为啥大模型LLM还没能完全替代你?
- 2024-04-2101-大语言模型发展
- 2024-04-17基于SpringWeb MultipartFile文件上传、下载功能