-2

I tried and succeed to build a quadratic equation solver.

public class Solver {
public static void main (String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
double positive = (-b + Math.sqrt(b*b-4*a*c))/2*a;
double negative = (-b - Math.sqrt(b*b-4*a*c))/2*a;
System.out.println("First answer is " + positive);
System.out.println("Second answer is " + negative);
} 
}

Sometimes I get NaN in the output. What did i do wrong?

Rona
  • 7

2 Answers2

1

NaN - not a number - is a value, that represents the result of invalid mathematical operations. Using real numbers, you cannot compute a square root of negative number - so NaN is returned.

Another problem with your solution is /2*a fragment. Division and multiplication have equal priority, so parenthesis are necessary. Moreover, if a is equal to zero, Java will throw java.lang.ArithmeticException: / by zero - you need also to check it.

One possible solution will be:

if (a == 0) {
    System.out.println("Not a quadratic equation.");
    return;
}

double discriminant = b*b - 4*a*c;
if (discriminant < 0) {
    System.out.println("Equation has no ansewer.");
} else {
    double positive = (-b + Math.sqrt(discriminant)) / (2*a);
    double negative = (-b - Math.sqrt(discriminant)) / (2*a);
    System.out.println("First answer is " + positive);
    System.out.println("Second answer is " + negative);
}
Artur Malinowski
  • 1,094
  • 12
  • 29
0

NaN stands for Not a Number. You have entered inputs that caused a mathematically undefined operation. so if the first number "a" is zero you will get that, and if b*b is greater than 4*a*c you will also get that message, the first situation is division by zero and the second is calculating the root of negative number.

Ahmed Wahbi
  • 118
  • 1
  • 2
  • 10