生成随机整数时无法包含上限 [英] Unable to include upper bound when generating random integer numbers

查看:29
本文介绍了生成随机整数时无法包含上限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个方法,它将生成一个 1 到 6 之间的无符号整数(包括边界).我目前的方法如下.

I am writing a method that will generate an unsigned int between 1 and 6 (boundaries included). The current method I have is below.

        private static Random random = new Random();
        ...
        private static uint GetRandomChannel()
        {
            return Convert.ToUInt32(random.Next(1, 6));
        }

我已经运行这个方法一千次了,我得到了数字 1 到 5,但从来没有得到过 6.为什么会发生这种情况,我该如何解决?

I've run this method a thousand times and I get numbers 1 through 5 but never get 6. Why is this happening and how can I fix it?

推荐答案

random.Next() 是一个独占上限.

参数

minValue:返回的随机数的包含下限.

minValue: The inclusive lower bound of the random number returned.

maxValue: 返回的随机数的唯一上限.maxValue 必须大于或等于 minValue.

maxValue: The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.

返回值

大于或等于 minValue 且小于 maxValue 的 32 位有符号整数;即返回值的范围包括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.

这意味着 random.Next(1, 6) 只会返回 n 范围内的值 1 <= n <;6.

This means that random.Next(1, 6) will only return values n in the range 1 <= n < 6.

因此对于您的模具滚动模拟,您需要使用

So for your die rolling simulation you will need to use

random.Next(1, 7)

<小时>

注意:这个 API 的设计很奇怪.它对 minValue == maxValue 有特殊情况处理,这似乎不必要地使 API 复杂化.如果我设计了这个 API,我会把两个参数都设为包含限制.这将产生令人愉悦的对称性,并允许随机数覆盖 int 的全部范围.


Note: The design of this API is odd. It has special case handling for minValue == maxValue which seems to needlessly complicate the API. If I had designed this API I would have made both parameters be inclusive limits. This would have resulted in a pleasing symmetry and would have allowed random numbers that cover the full range of int.

这篇关于生成随机整数时无法包含上限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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