-3

This code is to solve a quadric equation in Java. It output puts Nan. What is the wrong and how can I resolve this?

I tried a=1, b=2, c=10.

import java.util.*;

class equation {
  public static void main(String args[]) {
    int a, b, c;
    String input;
    Scanner key = new Scanner(System.in);

    System.out.println("Enter a value for a: ");
    a = key.nextInt();


    System.out.println("Enter a value for b: ");
    b = key.nextInt();


    System.out.println("Enter a value for c: ");
    c = key.nextInt();


    //finding roots
    double temp = Math.sqrt(b * b - 4 * a * c);

    double root1 = (-b + temp) / (2 * a);
    double root2 = (b + temp) / (2 * a);

    System.out.println("Answers are " + root1 + " or " + root2 + " .");
  }
}

enter image description here

Nimantha
  • 147
  • 4

3 Answers3

3

You get this result because you don't use Math#sqrt correctly.

b * b - 4 * a * c must be positive.


From the Math#sqrt Javadoc

◦If the argument is NaN or less than zero, then the result is NaN.


Addition (from @PeterLawrey)

So if you input a=1, b=2, c=10 then b * b - 4 * a * c is 4 - 40 or -36 and the square root is 6i which is an imaginary number which double doesn't support so Math#sqrt returns NaN.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
0

Always check possible domain conditions for your code to work.

From your question i am sure that you had given input where b*b-4*a*c<0 thats why it returned NAN

Here is complete code

    Scanner z = new Scanner(System.in):
    double first = z.nextInt();
    double second = z.nextInt();
    double third = z.nextInt();
    double d = (second * second - 4 * first * third);
    double re = -second / (2 * first);
     if (d >= 0) {  // i.e. "if roots are real"
        System.out.println(Math.sqrt(d) / (2 * first) + re);
        System.out.println(-Math.sqrt(d) / (2 * first) + re);
    } else {
      System.out.println(re + " + " + (Math.sqrt(-d) / (2 * first)) + "i");
      System.out.println(re + " - " + (Math.sqrt(-d) / (2 * first)) + "i");
    }
SmashCode
  • 741
  • 1
  • 8
  • 14
0

For a=1, b=2, c=10: Math.sqrt(b * b - 4 * a * c)means Math.sqrt(-38) The behaviour of Math.sqrt() is it retuns NAN if the parameter is negative( which is in your case).

Yashasvi Raj Pant
  • 1,274
  • 4
  • 13
  • 33