我知道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