作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想获得 1 和 0 之间的随机数。但是,我每次都得到 0。有人能解释我为什么总是得到 0 的原因吗?这是我试过的代码。
Random random = new Random();
int test = random.Next(0, 1);
Console.WriteLine(test);
Console.ReadKey();
最佳答案
根据documentation , Next
返回一个介于(含)最小值和(不含)最大值之间的整数随机数:
Return Value
A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.
唯一满足的整数
0 <= x < 1
是 0
,因此您总是得到值 0
。换句话说,0
是半闭区间 [0, 1)
内的唯一整数。
因此,如果您实际上对整数值 0
或 1
感兴趣,则使用 2
作为上限:
var n = random.Next(0, 2);
如果你想得到 0 到 1 之间的小数,试试:
var n = random.NextDouble();
关于c# - 如何在 C# 中生成 0 到 1 之间的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924871/
我是一名优秀的程序员,十分优秀!