C# Random Numbers aren#39;t being quot;randomquot;(C# 随机数不是“随机的;)
问题描述
我知道 C# Random 类不会生成真正的随机"数字,但我对这段代码提出了一个问题:
I know that the C# Random class does not make "true random" numbers, but I'm coming up with an issue with this code:
public void autoAttack(enemy theEnemy)
{
//Gets the random number
float damage = randomNumber((int)(strength * 1.5), (int)(strength * 2.5));
//Reduces the damage by the enemy's armor
damage *= (100 / (100 + theEnemy.armor));
//Tells the user how much damage they did
Console.WriteLine("You attack the enemy for {0} damage", (int)damage);
//Deals the actual damage
theEnemy.health -= (int)damage;
//Tells the user how much health the enemy has left
Console.WriteLine("The enemy has {0} health left", theEnemy.health);
}
然后我在这里调用该函数(为了检查数字是否随机,我调用了 5 次):
I then call the function here (I called it 5 times for the sake of checking if the numbers were random):
if (thePlayer.input == "fight")
{
Console.WriteLine("you want to fight");
thePlayer.autoAttack(enemy1);
thePlayer.autoAttack(enemy1);
thePlayer.autoAttack(enemy1);
}
但是,当我检查输出时,我得到的每 3 个函数调用的数字完全相同.但是,每次运行程序时,我都会得到一个不同的数字(重复 3 次),如下所示:
However, when I check the output, I get the exact same number for each 3 function calls. However, each time I run the program, I get a different number (which repeats 3 times) like this:
You attack the enemy for 30 damage.
The enemy has 70 health left.
You attack the enemy for 30 damage.
The enemy has 40 health left.
You attack the enemy for 30 damage.
The enemy has 10 health left.
然后我将再次重建/调试/运行程序,并得到一个不同的数字而不是 30,但它会重复所有 3 次.
I will then rebuild/debug/run the program again, and get a different number instead of 30, but it will repeat all 3 times.
我的问题是:如何确保每次调用此函数时都获得不同的随机数?我只是一遍又一遍地得到相同的随机"数字.
My question is: how can I make sure to get a different random number each time I call this function? I am just getting the same "random" number over and over again.
这是我使用的随机类调用:
Here is the random class call that I used:
private int randomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
推荐答案
我的猜测是 randomNumber
创建了一个新的 Random
每次...依次根据当前时间创建一个新的伪随机数生成器...这并不像您想象的那样经常变化.
My guess is that randomNumber
creates a new instance of Random
each time... which in turn creates a new pseudo-random number generator based on the current time... which doesn't change as often as you might think.
不要那样做.重复使用相同的 Random
实例...但 不要 通过创建静态 Random
变量来修复"它.从长远来看,这也不会很好,因为 Random
不是线程安全的.在测试中一切看起来都很好,然后在你碰巧并发不幸后你会神秘地得到全零:(
Don't do that. Use the same instance of Random
repeatedly... but don't "fix" it by creating a static Random
variable. That won't work well either in the long term, as Random
isn't thread-safe. It will all look fine in testing, then you'll mysteriously get all zeroes back after you happen to get unlucky with concurrency :(
幸运的是,使用线程局部变量并不难,特别是如果您使用的是 .NET 4.您最终会为每个线程创建一个新的 Random
实例.
Fortunately it's not too hard to get something working using thread-locals, particularly if you're on .NET 4. You end up with a new instance of Random
per thread.
我写了一篇关于这个主题的文章,您可能会觉得很有用,包括这段代码:
I've written an article on this very topic which you may find useful, including this code:
using System;
using System.Threading;
public static class RandomProvider
{
private static int seed = Environment.TickCount;
private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random>
(() => new Random(Interlocked.Increment(ref seed)));
public static Random GetThreadRandom()
{
return randomWrapper.Value;
}
}
如果您将 new Random()
调用更改为 RandomProvider.GetThreadRandom()
,这可能会完成您需要的一切(再次假设 .NET 4).这并没有解决可测试性,而是一步一步......
If you change your new Random()
call to RandomProvider.GetThreadRandom()
that will probably do everything you need (again, assuming .NET 4). That doesn't address testability, but one step at a time...
这篇关于C# 随机数不是“随机的";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 随机数不是“随机的";
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01