繁体   English   中英

java NaN和-infinity

[英]java NaN and -infinity

如果结果等于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。 :)

通过在使用前验证输入a,b和c,可以避免错误。

例:检查是否!= 0。

暂无
暂无

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

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