[英]I don't know where the infinite loop
So for my cs class, I had to write a program. 因此,对于我的CS类,我必须编写一个程序。 Long story short, I submit it to an autograder which provides feedback.
长话短说,我将其提交给提供反馈的自动分级机。 The autograder provides hints if we do not pass all the tests.
如果我们没有通过所有测试,自动分级机会提供提示。 One of the hints was that my code apparently seemed to go into an infinite loop for some test cases, but I do not know where this could possibly happen in my code.
提示之一是我的代码似乎在某些测试用例中陷入了无限循环,但是我不知道这可能在我的代码中发生什么地方。 Can someone point me in the right direction to where I may be going wrong?
有人可以指出我正确的方向,指出我可能会出问题的地方吗? I'll provide my code below:
我将在下面提供我的代码:
public class TwoLargest {
public static void main(String[] args){
double largest = Double.NEGATIVE_INFINITY;
double secondLargest = Double.NEGATIVE_INFINITY;
int numNums = 0;
System.out.print("Please enter a terminating value: ");
double termValue = IO.readDouble();
System.out.println("Please enter your list of numbers: ");
while(true){
double temp = IO.readDouble();
numNums++;
if((temp == termValue && numNums < 2) || temp == termValue && numNums == 2){
IO.reportBadInput();
numNums = 0;
System.out.println("Please try again: ");
continue;
}
if(temp == termValue){
break;
}
if (temp > largest) {
secondLargest = largest;
largest = temp;
}
else if (temp > secondLargest) {
secondLargest = temp;
}
}
IO.outputDoubleAnswer(largest);
IO.outputDoubleAnswer(secondLargest);
}
}
我可以看到,自动化工具将其视为潜在的无限循环,是用户不断输入最终值的情况。
One issue I see with the code you've provided is the comparison of doubles using ==
. 我看到的与您提供的代码有关的一个问题是使用
==
比较双打。 By using equals, you may never see the terminal. 通过使用等于,您可能永远都看不到终端。
You'll probably want to change the equals to something like this: Math.abs(temp - termValue) < 1e-6
您可能需要将等于更改为以下内容:
Math.abs(temp - termValue) < 1e-6
One other scenario that could result in an infinite loop is if the terminal is NaN, because NaN != NaN. 可能导致无限循环的另一种情况是终端是否为NaN,因为NaN!= NaN。
Also, for reference: Test for floating point equality. 另外,作为参考: 测试浮点相等性。 (FE_FLOATING_POINT_EQUALITY)
(FE_FLOATING_POINT_EQUALITY)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.