Vishal - 4 months ago 33

Java Question

So I'm trying to code this equation using java:

I'm taking a, b, and c from the user.

This is the code I have so far:

`import java.util.Scanner;`

class QaudraticFunction{

public static void main(String []args){

Scanner input = new Scanner(System.in);

System.out.println("Enter a: ");

double a = input.nextDouble();

System.out.println("Enter b: ");

double b = input.nextDouble();

System.out.println("Enter c: ");

double c = input.nextDouble();

double val1 = (Math.pow(b,2.0)) - (4.0*a*c);

double discriminant = Math.sqrt(val1);

double val2 = (-b)-(discriminant);

double r2 = val2/(2.0*a);

System.out.println("r2 = " + r2);

}

}

I think my issue is a logical error because the program compiles and runs correctly. When I enter the values for a, b and c. I get r2 = NaN

Answer

Two possible reasons you are seeing a `NaN`

.

The denominator is `0`

. This is only possible if `a`

is set to `0`

or `0.0`

. I'm going to assume that's not the case.

The other possibility is that you are performing a square root of a negative number, which (in java) is a NaN. See Math.sqrt javadoc for more details.

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