0

我希望 Quadratic 程序只打印必要的输出。这是代码:

public static void main(String[] args) {

    double a = Double.parseDouble(args[0]); 
    double b = Double.parseDouble(args[1]); 
    double c = Double.parseDouble(args[2]);
    double temp, first, second;
    temp = (b*b - (4 * a * c));
    first = ((-1 * b) + Math.sqrt(temp)) / (2 * a);
    second = ((-1 * b) - Math.sqrt(temp)) / (2 * a);
    if (temp > 0)
        System.out.println (first);
    if (temp == 0)
      if (first == second)
          System.out.println (first);
      else
        System.out.println (first);
        System.out.println (second);
    if (temp < 0)
        System.out.println ("There are no solutions.");
}

当我在写:java Quadratic 1 0 1 时,它带回:“NaN 没有解决方案。” 什么是 NaN?

当我写:java Quadratic 1 -2 1 它打印两次:“1.0 1.0”。我如何变成一个人?因为我已经写了这个 if 命令:if (first == second)。

太感谢了!!!

4

2 回答 2

0
temp = (b*b - (4 * a * c));

当 b = 0 时,变为:

temp = -(4 * a * c);

当 a 和 c 为正时, temp 为负,您不能取负数的平方根。

于 2015-11-06T19:02:48.110 回答
0

NaN 问题在此处以及该问题的评论和答案中的各种链接中得到解答。

多个输出可能是因为最后一个else. 即使您已经缩进了代码,看起来这两个printlns 仅在temp == 0和时执行first != second,但它们不是,只有第一个println在 中else,第二个每次都会执行。而是使用:

else {
    System.out.println(first);
    System.out.println(second);
}
于 2015-11-06T18:59:27.490 回答