0

I want that the Quadratic program will print only the necessary output. this is the code:

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.");
}

When I'm writing: java Quadratic 1 0 1 it brings back: "NaN There are no solutions." What is the NaN?

and when I'm writing: java Quadratic 1 -2 1 it prints twice: "1.0 1.0". How do I turn in into one? because i've already wrote this if command: if (first == second).

Thank you so much!!!

azurefrog
  • 10,785
  • 7
  • 42
  • 56
Loren
  • 95
  • 10

2 Answers2

0

The NaN question is answered here and in the various links in the comments and answers to that question.

The multiple outputs is probably because of the very last else. Even though you've indented the code such that it looks like the two printlns are only executed if temp == 0 and first != second, they aren't, only the first println is in the else, the second will get executed every time. Instead used:

else {
    System.out.println(first);
    System.out.println(second);
}
Community
  • 1
  • 1
blm
  • 2,379
  • 2
  • 20
  • 24
  • Hey, Thank you so much! It did work but there's still a problem when there are 2 answers. For example, for "java Quadratic 1 1 -2" - It prints only "1.0", even thought it should print 1.0 and -2.0. – Loren Nov 06 '15 at 19:09
  • @Dana In that case `temp` is 9 (1 * 1 - (4 * 1 * -2) = 1 - -8 = 9), so it's going into the `if (temp > 0)` and printing `first`. – blm Nov 06 '15 at 19:15
  • I fixed it! Thank you :) – Loren Nov 06 '15 at 19:35
0
temp = (b*b - (4 * a * c));

when b = 0, this becomes:

temp = -(4 * a * c);

which when a and c are positive results in temp being negative, and you can't take the square root of a negative number.