簡體   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