我试图让我的程序输出 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/