我知道C#Random类不会使“真正的随机”的数字,但我想出一个问题与此代码:C#随机数是不是“随机”
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次检查的缘故,如果数字是随机的):
if (thePlayer.input == "fight")
{
Console.WriteLine("you want to fight");
thePlayer.autoAttack(enemy1);
thePlayer.autoAttack(enemy1);
thePlayer.autoAttack(enemy1);
}
然而,当我检查输出,我得到每3所函数调用的同一号码。然而,每一个我运行程序时,我得到一个不同的号码(重复3次)这样的:
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次。
我的问题是:我怎么能确保每个我调用这个函数的时间去不同的随机数?我只是一遍又一遍地得到相同的“随机”数字。
这里是随机级呼叫,我用:
private int randomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
你的'randomNumber'函数是什么样的? – Nija
你可能想看看[这篇文章](http://www.codeducky.org/random-numbers-c-net-primer/),它讨论了这个问题以及.NET Random类的其他陷阱 – ChaseMedallion