gpt4 book ai didi

java - 二次公式程序 - 出现 NaN 错误

转载 作者:行者123 更新时间:2023-12-01 07:28:25 25 4
gpt4 key购买 nike

我不确定我的代码中做错了什么,但我无法让它正常运行...测试器不断返回 NaN 而不是预期的结果。本练习的目标是打印二次方程的所有实数解。 Solution1 应返回较小的解决方案,solution2 应返回较小的解决方案。这是我的类(class)。

   public class QuadraticEquation
{
private int a;
private int b;
private int c;
private boolean hasSolutions;
private double discriminant = (b * b) - (4 * a * c);
private double solution1;
private double solution2;
/**
* Constructs a quadratic equation
* @param a coefficient a
* @param b coefficient b
* @param c coefficient c
*/

public QuadraticEquation(int a, int b, int c)
{
a = a;
b = b;
c = c;
}
/**
* Checks if there is a solution
* @return true if there is a real solution
*/

public boolean hasSolutions()
{
if(discriminant < 0)
hasSolutions = false;
else
hasSolutions = true;
return hasSolutions;
}
/**
* Returns first solution
* @return first solution
*/

public double getSolution1()
{
if(hasSolutions)
{
if((-b + Math.sqrt(discriminant) / (2 * a)) < (-b - Math.sqrt(discriminant) / (2 * a)))
solution1 = (-b + Math.sqrt(discriminant) / (2 * a));
else
solution1 = (-b - Math.sqrt(discriminant) / (2 * a));
}
return solution1;
}
/**
* Returns second solution
* @return second solution
*/

public double getSolution2()
{
if(hasSolutions)
{
if((-b + Math.sqrt(discriminant) / (2 * a)) > (-b - Math.sqrt(discriminant) / (2 * a)))
solution2 = (-b + Math.sqrt(discriminant) / (2 * a));
else
solution2 = (-b - Math.sqrt(discriminant) / (2 * a));
}
return solution2;
}

}

这是我的测试仪:

    public class QuadraticEquationTester
{
public static void main(String[] args)
{
QuadraticEquation equation = new QuadraticEquation(2, 2, -4);
System.out.println(equation.hasSolutions());
System.out.println("Expected: true");
System.out.println(equation.getSolution1());
System.out.println("Expected: -2");
System.out.println(equation.getSolution2());
System.out.println("Expected: 1");

QuadraticEquation equation2 = new QuadraticEquation(2, 2, 4);
System.out.println("\n" + equation2.hasSolutions());
System.out.println("Expected: false");
System.out.println(equation2.getSolution1());
System.out.println("Expected: 0");
System.out.println(equation2.getSolution2());
System.out.println("Expected: 0");
}
}

非常感谢! :)

最佳答案

  1. 您正在类上下文的对象初始化部分中计算判别式,该部分使用默认值a、b 和c 进行计算。在初始化 a,bc

  2. 之前不要计算
  3. 您在构造函数方法中隐藏了变量,因为 a、b、c 是参数字段。使用这个:

    public QuadraticEquation(int a, int b, int c)
    {
    this.a = a;
    this.b = b;
    this.c = c;
    }
  4. NaN 通过零除以零等运算进行浮点计算。所以找出上述修复后是否仍然发生这种情况。

关于java - 二次公式程序 - 出现 NaN 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20753021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com