如何为if语句“声明”NaN? [重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我有一个二次公式求解器的代码,但我不能让NaN用我的if语句来表现。

package homework;
import java.util.Scanner;
import java.lang.Math;
//                          My Name 9/18/18 
// The purpose of this class is to allow a user to input an a,b, and c     value     and perform the quadratic equation on them
public class QuadFormHW 
{

public static void main(String[] args) 
{
    double a,b,c,answer1,answer2;
    Scanner inputReader = new Scanner(System.in);
    System.out.print("Please enter an \"a\" \"b\" and \"c\" value.");
    a = inputReader.nextDouble();
    b = inputReader.nextDouble();
    c = inputReader.nextDouble();
    answer1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
    answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
    if (answer1 == NaN)
    {
        System.out.print("Error cannot calculate");
    }
    else if (answer2 == NaN)
    {
        System.out.print("Error cannot calculate");
    }
    else
    {
        System.out.printf("Your answers are: %.3f , %.3f",answer1,answer2); 
    }
    inputReader.close();
}

}

任何人都可以帮助我理解为什么NaN不是一个可接受的价值?

java variables if-statement nan
1个回答
0
投票

你提出的问题与这个较旧的QA帖子一样:How do you test to see if a double is equal to NaN?(我已将此标记为重复)。

简而言之:根据设计,NaN无法与任何其他值进行有意义的比较,(因此foo == NaN不适用于您的目的)。这是因为NaN传播。

相反,要测试NaN,请使用Double.isNaN( value )Float.isNaN( value )

© www.soinside.com 2019 - 2024. All rights reserved.