当我使用调试器逐步执行程序时,它可以正常工作并显示正确的结果。但是,当我运行程序时,它会为homeTeamRuns和awayTeamRun显示一些极高的数字。我似乎无法弄清楚问题。
class BallGame
{
//Fields
private string output = "";
int outs = 0;
int runs = 0;
int homeTeamRuns = 0;
int awayTeamRuns = 0;
bool homeTeam = false;
bool awayTeam = false;
int[] innings = new int[12]; //Innings
//Properties
public string Output
{
get
{
return output;
}
set
{
output = value;
}
}
//Game Simulator
public void playBall()
{
int[] play = new int[4]; //Bases
for(int i = 1; i <= 2; i++)
{
homeTeam = false;
awayTeam = false;
if(i%2 == 0)
homeTeam = true;
else
awayTeam = true;
//Half Inning
while (outs < 3)
{
bool yourOut = false, single = false, double1 = false, triple = false, homerun = false;
Random rnd1 = new Random();
int randomNum = rnd1.Next(1, 101);
//
if (randomNum >= 1 && randomNum <= 50) //50% chance
yourOut = true;
else if (randomNum > 50 && randomNum <= 60) //10% chance
single = true;
else if (randomNum > 60 && randomNum <= 92) //42% chance
double1 = true;
else if (randomNum > 92 && randomNum <= 97) //5% chance
triple = true;
else if (randomNum > 97 && randomNum <= 100) //%3 chance
homerun = true;
if (yourOut == true)
{
outs++;
}
else if (single == true)
{
Shift(play);
runScored(play);
play[0] = 1;
}
else if (double1 == true)
{
Shift(play);
runScored(play);
Shift(play);
runScored(play);
play[1] = 1;
}
else if (triple == true)
{
Shift(play);
runScored(play);
Shift(play);
runScored(play);
Shift(play);
runScored(play);
play[2] = 1;
}
else if (homerun == true)
{
Shift(play);
runScored(play);
Shift(play);
runScored(play);
Shift(play);
runScored(play);
Shift(play);
runScored(play);
play[3] = 1;
}
play[3] = 0;
if (outs == 3)
{
play[0] = 0;
play[1] = 0;
play[2] = 0;
play[3] = 0;
}
}
outs = 0;
}
output = "Home Team Runs: " + homeTeamRuns + " Away Team Runs: " + awayTeamRuns;
}
//Shift Array
public int[] Shift(int[] array)
{
for (int i = array.Length -1; i >= 1; i--)
{
array[i] = array[i - 1];
}
array[0] = 0;
return array;
}
public void runScored(int[] array)
{
if(array[3] == 1)
{
if(awayTeam == true)
awayTeamRuns++;
else if(homeTeam == true)
homeTeamRuns++;
}
}
}
答案 0 :(得分:2)
您正在循环的每次迭代中创建Random
类的新实例。您正在使用的构造函数的documentation表示:
使用与时间相关的默认种子值初始化Random类的新实例。
由于循环在您不进行调试时执行得非常快,因此最终会在多次迭代中使用相同的种子,因此对Next
的调用每次都返回相同的值。如果该值碰巧是一个会增加分数的值,那么分数将在循环的多次迭代中递增。
移动线
Random rnd1 = new Random();
在您的for
循环上方将构建一个Random
实例,然后为每次调用Next
创建一个新的随机数。
在调试器中运行时无法重现这一点,因为在创建新Random
实例时时钟已经移动,因此种子已更改。
有关Random
实例返回相同值的更多信息,请参阅this StackOverflow帖子。此外,Jon Skeet在使用Random类时有blog post覆盖陷阱,这非常值得一读。