Search code examples
javaquadratic-programming

Quadratic programming - specific output


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!!!


Solution

  • 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.