有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的二次方程求解器

我尝试并成功地建立了一个二次方程求解器

public class Solver {
public static void main (String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
double positive = (-b + Math.sqrt(b*b-4*a*c))/2*a;
double negative = (-b - Math.sqrt(b*b-4*a*c))/2*a;
System.out.println("First answer is " + positive);
System.out.println("Second answer is " + negative);
} 
}

有时我在输出中得到NaN。 我做错了什么


共 (1) 个答案

  1. # 1 楼答案

    NaN不是数字,是一个值,表示无效数学运算的结果。使用实数时,无法计算负数的平方根,因此返回NaN

    解决方案的另一个问题是/2*a片段。除法和乘法的优先级相同,所以括号是必要的。此外,如果a等于零,Java将抛出java.lang.ArithmeticException: / by zero——您还需要检查它

    一个可能的解决方案是:

    if (a == 0) {
        System.out.println("Not a quadratic equation.");
        return;
    }
    
    double discriminant = b*b - 4*a*c;
    if (discriminant < 0) {
        System.out.println("Equation has no ansewer.");
    } else {
        double positive = (-b + Math.sqrt(discriminant)) / (2*a);
        double negative = (-b - Math.sqrt(discriminant)) / (2*a);
        System.out.println("First answer is " + positive);
        System.out.println("Second answer is " + negative);
    }