【问题标题】:Quadratic equations solver in java [closed]java中的二次方程求解器[关闭]
【发布时间】:2014-05-18 19:40:51
【问题描述】:

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

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。 我做错了什么?

【问题讨论】:

  • 对于什么输入值?
  • 那么您提供了什么意见?我怀疑你给出的值是没有没有解决方案。 (即 b^2 - 4ac 是负数。)
  • 你需要处理a=0b*b-4*a*c是否定的情况。
  • 我会将 a、b 和 c 声明为 double,有时您会遇到整数/双精度运算冲突(尤其是除法时),但似乎并非如此。
  • 你需要把分母放在括号里:x/2*a -> x/(2*a)

标签: java quadratic


【解决方案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);
}

【讨论】:

  • 谢谢。您是否将第一个替身设为判别式?
  • @Rona 是的,这是一个错字。
【解决方案2】:

NaN 代表非数字。您输入了导致数学上未定义的操作的输入。所以如果第一个数字“a”是零,你会得到,如果 b*b 大于 4*a*c,你也会得到那个消息,第一种情况是除以零,第二种情况是计算根负数。

【讨论】:

  • 如何防止 Nan?
猜你喜欢
  • 2022-06-11
  • 1970-01-01
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多