Random number: 0 or 1

十年热恋 提交于 2021-02-07 11:15:26

问题


Am I looking too far to see something as simple as pick a number: 0 or 1?

        Random rand = new Random();

        if (rand.NextDouble() == 0)
        {
            lnkEvents.CssClass = "selected";
        }
        else
        {
            lnkNews.CssClass = "selected";
        }

回答1:


Random rand = new Random();

if (rand.Next(0, 2) == 0)
    lnkEvents.CssClass = "selected";
else
    lnkNews.CssClass = "selected";

Random.Next picks a random integer between the lower bound (inclusive) and the upper bound (exclusive).




回答2:


If you want 50/50 probability, I suggest:

Random rand = new Random();

if (rand.NextDouble() >= 0.5)
    lnkEvents.CssClass = "selected";
else
    lnkNews.CssClass = "selected";



回答3:


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.

const int ExclusiveUpperBound = 2;
if (new Random().Next(ExclusiveUpperBound) == 0)

The value produced is "greater than or equal to zero, and less than" ExclusiveUpperBound.




回答4:


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.




回答5:


If not in a tight loop you could use

(DateTime.Now.Millisecond % 2) - double DateTime.Now.Millisecond % (double) 10) / 10



回答6:


A very simple approach could be:

Random random = new Random();
bool result = random.Next(0, 2) != 0;

Then use result for your logic.



来源:https://stackoverflow.com/questions/1493051/random-number-0-or-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!