【问题标题】:How to "declare" NaN for a if statement? [duplicate]如何为 if 语句“声明” NaN? [复制]
【发布时间】:2019-02-23 01:27:12
【问题描述】:

我有一个二次公式求解器的代码,但我的 if 语句无法让 NaN 运行。

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 不是一个可接受的值?

【问题讨论】:

  • 改用 Float.NaN 吗?
  • 在这种非常特殊的情况下,您可以检查所有会出现 NaN 的地方,而无需执行计算:Math.sqrt(x) 是 NaN,如果 x < 0x/y 是 NaN,如果 y 是0. 在你计算之前做:double toCheck = Math.pow(b, 2) - (4 * a * c); if(toCheck < 0 || a == 0) { /* would be NaN */ } 并且只在这些都不会导致 NaN 的情况下计算其余部分。

标签: java variables if-statement nan


【解决方案1】:

您问的问题与以前的 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 )

【讨论】:

  • 你为什么要发布一个总结另一个答案的答案,特别是如果你投票关闭为重复?
  • 非常感谢这解决了我的问题。
  • @MadPhysicist 对链接问题的接受答案有错误,哈哈。至少这个从一开始就是正确的。
  • @MadPhysicist 我想在问题作为副本关闭之前向 OP 提供一个有用的答案,以防 OP 没有看到 Dupe 链接。
  • 有道理,尤其是考虑到冥王星的评论
猜你喜欢
  • 2013-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 2021-01-17
  • 1970-01-01
  • 2014-04-12
  • 2014-08-26
相关资源
最近更新 更多