c# - 随机数表现怪异,不是完全随机的

标签 c# .net visual-studio-2010

在我的 .NET 游戏中,我的 rand 函数确定五个角色中的每个玩家应该承受多少伤害,但是第一个似乎总是在比例尺的底部而最后一个在顶部。所以在我的 Character[0] 中,伤害很少比最小 rand 值多 1,并且对于较高索引上的每个 Character,受到的伤害只是从较高索引中随机产生的扩大规模。

public int GetDamage(int low, int high)
{
    Random r = new Random();
    int rand = r.Next(low, high);
    return rand;
}

这是我使用的随机发生器。然后我像这样更新剩余的健康状况:

int Damage = GetDamage(3, 10);
Characters[Target].Health = Characters[Target].Health - Damage;

在这个例子中,dmg 是这样划分的:

Number 1: 3-4
Number 2: 4-6
Number 3: 5-7
Number 4: 7-8
Number 5: 8-9

最佳答案

您必须重复使用同一个随机实例,否则您将无法获得真正的随机值,因为它是用当前时间作为种子创建的。如果您非常快地调用 GetDamage(例如在循环中),您将始终获得相同的值。

因此要么使用 GetDamage 类中的字段/属性,要么将随机实例传递给该方法。

private Random _rnd = new Random();
public int GetDamage(int low, int high)
{
    int rand = _rnd.Next(low, high);
    return rand;
}

MSDN

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers. This problem can be avoided by creating a single Random object rather than multiple ones.

关于c# - 随机数表现怪异,不是完全随机的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15949417/

相关文章:

c# - WCF 服务调用包装器

.net - 学习 Silverlight 的最佳方法是什么?

c# - .NET Core SDK 版本 2.2.202 的 MSBuild 失败

c# - Screen.AllScreens 的奇怪体验

c# - Json.net JsonIgnore 不适用于嵌套类

c# - 在 C# 中获取 GetWeekOfYear 的日期?

c++ - VC++的迭代器声明

c# - 我可以自动将代码和新类放入我的解决方案的很多部分吗?

visual-studio-2010 - 保存项目时删除了 using 语句

c# - 使用 System.Text.Json 将 JSON 反序列化为对象