C# 随机函数返回相同的值 [英] C# random function returning the same value

查看:32
本文介绍了C# 随机函数返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
随机数生成器没有按照我计划的方式工作(C#)

我做了一个生成随机数的简单例程

I have made a simple routine which generates a random number

private int randomNumber()
{
    Random random = new Random();
    int randomNum = random.Next(0, 100);
    Response.Write(randomNum);
    return randomNum;
}

我在整个 page_load 的两个不同阶段以相同的方式调用它:

I call this at two different stages throughout my page_load in the same way:

// A/B Test
if (randomNumber() <= 50)
{
...

不过,我发现这两个数字总是相同的.有什么想法吗?

I'm finding though, that both numbers are always the same. Any ideas?

推荐答案

当您创建一个 Random 实例时,它会被植入当前时间.因此,如果您同时创建多个它们,它们将生成相同的随机数序列.您需要创建 Random 的单个实例并使用它.

When you create a Random instance it's seeded with the current time. So if you create several of them at the same time they'll generate the same random number sequence. You need to create a single instance of Random and use that.

这篇关于C# 随机函数返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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