【发布时间】:2011-11-07 06:42:29
【问题描述】:
我知道 C# Random 类不会生成“真正的随机”数字,但我在这段代码中遇到了问题:
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函数是什么样的?