如果结果等于NaN或-infinity,则我无法找出一种捕捉或下达程序的方法。
每当我在程序中输入0时,都会得到NaN和-Infinity的结果。
我面临的问题是x1和x2是双精度类型,显然不能与String类型进行比较。任何帮助将非常感激。

public class Exercise {

public static void main(String[] args){
    double x1 = 0;
    double x2 = 0;

    Scanner scanner = new Scanner(System.in);

    System.out.println("Feed me with a, b and c");

    try{
            double a = scanner.nextDouble();
            double b = scanner.nextDouble();
            double c = scanner.nextDouble();
            scanner.close();
            double discriminant = (b * b) - 4 * (a * c);

        if (discriminant > 0){

            x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
            x2 = (-b - Math.sqrt(discriminant)) / (2 * a);

            System.out.println("The dish of yours has two components " + x1
        + " and " + x2);
        }

        if (discriminant == 0){

            x1 = -b / (2 * a);
            System.out.println("The dish of yours has two identical
        components " + x1 +" and " + x1);

        }

        if (discriminant < 0){

            System.out.println("The dish of yours doesn't have any
         component");

        }

        }
        catch (InputMismatchException e) {
            System.out.println("I can't digest letters");
        }
        catch (Exception e) {
            System.out.println("This is inedible");
    }
    }
    }

最佳答案

您可以通过执行以下操作来检查NaN:

if (Double.isNaN(yourResult)) { ... }

通过执行以下操作来实现无穷大:
if (Double.isInfinite(yourResult)) { ... }

永远不要使用==检查NaN,因为NaN被认为不等于NaN!

或者,您可以仅检查a是否为0。因为这可能是Infinity和NaN出现的唯一情况。如果是这样,请说“我的菜在哪里?”之类的话。 :)

另外,我只是尝试给出Nan NaN NaN而它什么也不输出。考虑检查a,b和c是否也是NaN或Infinities。 :)

10-02 06:54
查看更多