为什么C#的随机下限包括在内,但上限不包括在内? [英] Why is C#'s random lower limit inclusive, but upper limit exclusive?

查看:147
本文介绍了为什么C#的随机下限包括在内,但上限不包括在内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下面的代码为例:

Random rnd = new Random();
int rndNumber = rnd.Next(0,101);

有人希望会发生以下任一情况:
-rndNumber包含一个介于0到101之间的随机整数
-rndNumber包含1到100之间的随机整数

One would expect that either one of the following would happen:
-rndNumber contains a random integer between 0 and 101
-rndNumber contains a random integer between 1 and 100

实际上是什么,rndNumber包含一个0到100之间的随机整数.为什么会这样?

What actually happens though, is that rndNumber contains a random integer between 0 and 100. Why is this the case?

我知道上限是互斥的,但是为什么下限是互斥的呢?为什么这不一致?

I understand that the upper limit is exclusive, but then why is the lower limit inclusive? Why is this not consistent?

推荐答案

此方法与使用零作为其初始元素的编号方案一致.在某些情况下这很方便,因为您不必执行任何算术运算,也不必面对罕见的一次性错误.

This approach is consistent with numbering schemes that use zero as their initial element. This is convenient in several situations, because you do not have to do any arithmetic or face rare off-by-one errors, for example

当您选择数组的随机元素时:

var rndElement = myArray[rnd.Next(0, myArray.Length)];

当您在几个点上分割一个间隔,并从每个子间隔中选择随机元素时:

var endpoints = new[] {0, 10, 17, 36, 80};
for (int i = 0 ; i+1 < endpoints.Length ; i++) {
    var from = endpoints[i];
    var to = endpoints[i+1];
    Console.WriteLine("({0}..{1}) : {2}", from , to, rnd.Next(from, to));
}

这也使计算可以生成多少个不同值的操作变得更加容易.

It also makes it easier to compute how many different values can be generated.

这篇关于为什么C#的随机下限包括在内,但上限不包括在内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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