【问题标题】:Can't figure out why this is causing an infinite loop无法弄清楚为什么这会导致无限循环
【发布时间】:2012-07-01 17:04:02
【问题描述】:

所以我有这行代码,它时不时地生成一个无限循环。我的逻辑在某处不正确吗? "if (randomNumbersForSelectionArray.Count > 0)" 中的 if 语句应该总是返回 true,但事实并非如此。然后,当我执行 else 语句并检查代码进入无限循环时是否应该为真时,它确认我的逻辑应该是正确的。我似乎无法弄清楚这是哪里出了问题。谢谢!!


这是我得到的一些示例输出。

12| 2 =应该= 2
为什么会这样!?!?!?
12| 2 =应该= 2
为什么会破!?!?!?
...无限


int countLoop = 0;

如果 (trackFitnessRankArray.Length >= 1) {

            while (randomNumbersForSelectionArray.Count > 0)
            {
                countLoop++;

                for (int j = trackFitnessRankArray.Length - 1; j >= 0; j--)
                {
                    if (randomNumbersForSelectionArray.Count > 0)
                    {
                        if (randomNumbersForSelectionArray[0] >= (trackFitnessRankArray[j].CutoffPointForReproduction - trackFitnessRankArray[j].ChanceOfReproduction) && randomNumbersForSelectionArray[0] < trackFitnessRankArray[j].CutoffPointForReproduction)
                        {
                            //take the selected AIs and put them in an array
                            selectedToBreed.Add(trackFitnessRankArray[j]);

                            //remove the number from the randomNumber array
                            randomNumbersForSelectionArray.RemoveAt(0);
                        }
                        else
                        {
                            //if we're in an infinite loop
                            if (countLoop > AI_IN_EACH_GENERATION)
                            {
                                if (randomNumbersForSelectionArray[0] == trackFitnessRankArray[j].CutoffPointForReproduction)
                                {
                                    if (j != 0)
                                        Debug.WriteLine(j + "| " + randomNumbersForSelectionArray[0] + " =should= " + (trackFitnessRankArray[j - 1].CutoffPointForReproduction + trackFitnessRankArray[j - 1].ChanceOfReproduction));
                                    if (randomNumbersForSelectionArray[0] != (trackFitnessRankArray[j - 1].CutoffPointForReproduction + trackFitnessRankArray[j - 1].ChanceOfReproduction))
                                        Debug.WriteLine("Why is this breaking!?!?!?");
                                }
                            }
                        }
                    }
                }
            }
        }

【问题讨论】:

    标签: for-loop while-loop logic infinite-loop


    【解决方案1】:

    组件

    //remove the number from the randomNumber array
                                randomNumbersForSelectionArray.RemoveAt(0);
    

    应该在if之外

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 2013-06-17
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多