[英]My code hangs when trying to determine random number with probability
我正在編寫一個模擬網球比賽的程序。 對於那些知道規則的人來說非常簡單,但這是我的快速回顧:每位玩家必須獲得4分,並且如果他未領先2分,則玩家將繼續比賽直到其中一位得分超過對手2分或更多一個游戲。 贏得一組相同的規則-需要比對手多2點。 在用戶輸入X套游戲后游戲結束。
非常簡單,但是我也實現了確定玩家A技能的變量。 例如,如果玩家的技能超過60,則理論上他贏得比賽的機會更大。
這是我的代碼。 問題是,如果我將numberOfSets
變量設置為10並將playerSkill
變量playerSkill
為大於55或小於45的任何值,程序將掛起,CPU使用率將上升(不是很多,我只看到了小峰值,大約為15%) ),除了停止該程序外,我無能為力。 如果我將numberOfSets
變量設置為較低的值(例如1或2),則程序似乎可以正常運行,即使在使用playerSkill
愚蠢值(例如1或99)的情況下,我也很playerSkill
,因此我肯定省略了一些內容,這很明顯,還是我做過,不應該做的非常愚蠢的事情。
int playerAGamesWon = 0;
int playerBGamesWon = 0;
int playerSkill = 50;
int numberOfSets = 10;
int numberOfGames = 6;
int numberOfPoints = 4;
void SimulateTennis()
{
txtData.Text = "Simulating game of tennis"+Environment.NewLine;
Random rand = new Random();
for (int i = 0; i < numberOfSets; i++)
{
while (true)
{
calculatePlayerPoints(rand);
if (playerAGamesWon >= numberOfGames || playerBGamesWon >= numberOfGames)
{
if (playerAGamesWon - playerBGamesWon >= 2)
{
playerASetWon++;
txtData.Text += "Player A won the Set with " + playerAGamesWon + " games to " + playerBGamesWon + Environment.NewLine + Environment.NewLine;
playerAGamesWon = 0;
playerBGamesWon = 0;
break;
}
else if (playerBGamesWon - playerAGamesWon >= 2)
{
playerBSetWon++;
txtData.Text += "Player B won the Set with "+ playerBGamesWon + " games to " + playerAGamesWon + Environment.NewLine + Environment.NewLine;
playerAGamesWon = 0;
playerBGamesWon = 0;
break;
}
else
{
continue;
}
}
}
}
}
void calculatePlayerPoints(Random rand)
{
int apoints = 0;
int bpoints = 0;
while (true)
{
int prob = rand.Next(100);
if (prob <= playerSkill)
{
apoints++;
}
else
{
bpoints++;
}
if (apoints >= numberOfPoints)
{
if (apoints - bpoints >= 2)
{
playerAGamesWon++;
updateScoreText(apoints, bpoints);
break;
}
}
//else if statement of (bpoints >= numberOfPoints) was unreachable when if statement of (apoints >= numberOfPoints) was true
//I should use if statement
//else if (bpoints >= numberOfPoints)
if (bpoints >= numberOfPoints)
{
if (bpoints - apoints >= 2)
{
playerBGamesWon++;
updateScoreText(apoints, bpoints);
break;
}
}
}
}
您在calculatePlayerPoints
方法中輸入無限循環。 如果比較apoints
和numberOfPoints的結果為true
,但條件if (apoints - bpoints> = 2)
為false
,則不會進行bpoints
和numberOfPoints
的比較。 您必須在else if (bpoints> = numberOfPoints)
刪除else
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.