如何在C#中生成0到1之间的随机数? [英] How do I generate random number between 0 and 1 in C#?

查看:2254
本文介绍了如何在C#中生成0到1之间的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得1到0之间的随机数。但是,我每次都得到0。有人可以向我解释为什么我总是得到0的原因吗?
这是我尝试过的代码。

I want to get the random number between 1 and 0. However, I'm getting 0 every single time. Can someone explain me the reason why I and getting 0 all the time? This is the code I have tried.

Random random = new Random();
int test = random.Next(0, 1);
Console.WriteLine(test);
Console.ReadKey();


推荐答案

根据文档下一步返回介于(包括)的最小值和(最大值):

According to the documentation, Next returns an integer random number between the (inclusive) minimum and the (exclusive) maximum:


返回值

一个32位有符号整数,大于或等于minValue且小于maxValue;也就是说,返回值的范围包括minValue但不包括maxValue。如果minValue等于maxValue,则返回minValue。

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)内的唯一整数。

is 0, hence you always get the value 0. In other words, 0 is the only integer that is within the half-closed interval [0, 1).

因此,如果您实际上对整数值 0 1 ,然后使用 2 作为上限:

So, if you are actually interested in the integer values 0 or 1, then use 2 as upper bound:

var n = random.Next(0, 2);

如果您想获取0到1之间的小数,请尝试:

If instead you want to get a decimal between 0 and 1, try:

var n = random.NextDouble();

希望这会有所帮助:-)

Hope this helps :-)

这篇关于如何在C#中生成0到1之间的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆