简体   繁体   English

java NaN和-infinity

[英]java NaN and -infinity

I am failing to figure out a way to catch, or give order to my program if the result equals with NaN or -infinity. 如果结果等于NaN或-infinity,我没有想办法捕捉或命令我的程序。 Whenever I enter 0 into my program it gives me a result of NaN and -Infinity. 每当我在程序中输入0时,它会给我一个NaN和-Infinity的结果。 The problem I am facing is that the x1 and x2 are double types, that obviously can't be compared with String type. 我面临的问题是x1和x2是双重类型,显然无法与String类型进行比较。 Any help would be much appreciated. 任何帮助将非常感激。

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");
    }
    }
    }

You can check for NaN by doing 您可以通过执行来检查NaN

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

And infinities by doing: 无限性:

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

You should never use == to check for NaN because NaN is considered not equal to NaN ! 你永远不应该使用==检查NaN因为NaN被认为不等于NaN

Or, you can just check whether a is 0. Because that is probably the only case where Infinity and NaN will come out. 或者,您可以检查a是否为0.因为这可能是Infinity和NaN出现的唯一情况。 If it is, say something like "Where's my a dish?" 如果是,请说“我的菜在哪里?” :) :)

Also, I just tried giving Nan NaN NaN and it output nothing. 此外,我只是尝试给Nan NaN NaN并且它什么都没输出。 Consider checking whether a, b and c are NaN or Infinities as well. 考虑检查a,b和c是否也是NaN或Infinities。 :) :)

Simply your error can be avoided by validating your inputs a,b and c before using. 通过在使用前验证输入a,b和c,可以避免错误。

Ex : check whether a!=0. 例:检查是否!= 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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