C# 随机 - if 语句仅输出 = -1

标签 c# random

我试图让我的程序输出 1 或 -1 这是我目前的代码,它唯一的输出是 -1。这根本不是随机的。

Random rnd = new Random();
int L = rnd.Next(0, 1);
if (L == 0)
{
    Console.WriteLine(-1);
}
else
{
    Console.WriteLine(1);
}

最佳答案

第二个参数Random.Next(int, int)给出一个独占上限。所以你说你想要一个大于或等于 0 且小于 1 的整数。这并没有为 0 以外的数字提供很多范围 :)

来自文档:

Return Value
Type: System.Int32
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.

您还应该阅读我的 article on randomness以避免其他常见问题。

关于C# 随机 - if 语句仅输出 = -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19846457/

相关文章:

c# - Task.WaitAll 一直在循环

c# - 随机方向,没有重复..(错误描述)

c# - 递归遍历目录树并列出文件名

r - 如何在 R 中按州创建分层样本

c# - 重复获取相同的随机数

C++11 在 int x, int y 之间随机,不包括 list<int>

java - 在数组中生成随机数,将它们相加并将答案存储在数组中

python - 我如何在Python中获得一个随机日期以及3天后的日期?

c# - ADO.NET 和数据集中的丢失更新

c# - ASP.NET 中的全局变量