简体   繁体   中英

I don't know where the infinite loop

So for my cs class, I had to write a program. 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

One other scenario that could result in an infinite loop is if the terminal is NaN, because NaN != NaN.

Also, for reference: Test for floating point equality. (FE_FLOATING_POINT_EQUALITY)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM