方法显示不正确的结果

当我使用调试器单步执行程序时,它工作正常,并显示正确的结果。 但是,当我运行程序时,它会为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 = 1 && randomNum  50 && randomNum  60 && randomNum  92 && randomNum  97 && randomNum = 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++; } } } 

您正在循环的每次迭代中创建Random类的新实例。 您正在使用的构造函数的文档说:

使用与时间相关的默认种子值初始化Random类的新实例。

由于循环在您不进行调试时执行得非常快,因此最终会在多次迭代中使用相同的种子,因此对Next的调用每次都返回相同的值。 如果该值恰好是将增加分数的值,那么分数将在循环的多次迭代中递增。

移动线

 Random rnd1 = new Random(); 

在你的for循环之上将构造一个Random实例,然后为每次调用Next创建一个新的随机数。

在调试器中运行时无法重现这一点,因为在创建新的Random实例时时钟已经移动,因此种子已更改。

可以在此 StackOverflowpost中找到有关返回相同值的Random实例的更多信息。 此外,Jon Skeet有一篇博文,介绍使用Random类时的陷阱,这非常值得一读。