C# 随机数:0 或 1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1493051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random number: 0 or 1
提问by Rickjaah
Am I looking too far to see something as simple as pick a number: 0 or 1?
我是否看得太远而看不到像选择一个数字这样简单的东西:0 或 1?
Random rand = new Random();
if (rand.NextDouble() == 0)
{
lnkEvents.CssClass = "selected";
}
else
{
lnkNews.CssClass = "selected";
}
采纳答案by JDunkerley
Random rand = new Random();
if (rand.Next(0, 2) == 0)
lnkEvents.CssClass = "selected";
else
lnkNews.CssClass = "selected";
Random.Nextpicks a random integer between the lower bound (inclusive) and the upper bound (exclusive).
Random.Next在下限(含)和上限(不含)之间选择一个随机整数。
回答by Mitch Wheat
If you want 50/50 probability, I suggest:
如果你想要 50/50 的概率,我建议:
Random rand = new Random();
if (rand.NextDouble() >= 0.5)
lnkEvents.CssClass = "selected";
else
lnkNews.CssClass = "selected";
回答by Timbo
Random.NextDouble()
will select any double number from 0 but less than 1.0. Most of these numbers are not zero, so your distribution will not be as even as you expect.
Random.NextDouble()
将从 0 但小于 1.0 中选择任何双数。这些数字中的大多数都不是零,因此您的分布不会像您预期的那样均匀。
回答by bdukes
It seems like what you're wanting to do (choose between two values) is more clearly expressed by using the Next
method, instead of the NextDouble
method.
使用Next
方法而不是方法可以更清楚地表达您想要做什么(在两个值之间进行选择)NextDouble
。
const int ExclusiveUpperBound = 2;
if (new Random().Next(ExclusiveUpperBound) == 0)
The value produced is "greater than or equal to zero, and less than" ExclusiveUpperBound
.
产生的值是“大于或等于零,并且小于” ExclusiveUpperBound
。
回答by Knut d?rum
If not in a tight loop you could use
如果不是在一个紧密的循环中,你可以使用
(DateTime.Now.Millisecond % 2) - double DateTime.Now.Millisecond % (double) 10) / 10
回答by Alex Leo
A very simple approach could be:
一个非常简单的方法可能是:
Random random = new Random();
bool result = random.Next(0, 2) != 0;
Then use result for your logic.
然后将结果用于您的逻辑。