C# Methods: Need Help in creating a "custom" method

Hello there! This is my first time posting here. I’m sorry if this seems like a simple newbie error, I’ve been learning C# since last week and I’m still pretty new to all of this.

So: I wanted to create a “custom” method. A method that when you call it in Main( ) along with 3 double values, it returns you a value using the Cuadratic Formula.

static double CuadraticFormula(double a, double b, double c)
            double bPow = Math.Pow(b, 2);
            double ac = 4 * a * c;
            double e = Math.Sqrt(bPow - ac);
            return (b + e) / (2 * a);

The problem is that, when I print this method, for example:

Console.WriteLine(cuadraticFormula(2, 3, 4));

It returns NaN, instead of a double.
I tried changing the code so It’s more organized, but it always returns NaN. What am I doing wrong here?
It would be great if you could help me. Peace

1 Like

Hi and welcome to the forums!

The reason you’re getting NaN (Not a Number) is because of this line:

Math.Sqrt requires a positive number to return the square root as can be seen here.

The numbers you are passing in have a negative result, you’ll either have to change the values, or make the result of bPow - ac positive.

1 Like

Changing the value of e (by, say, taking the absolute value) might solve the programming error, but since we’re writing code here to solve a mathematical problem we cannot simply decide to change a term for our convenience. :slight_smile:

Whilst @louwding is correct about the source of your error, to understand why it’s producing that error we first need to understand the algebra behind the quadratic equation.

The variables inside of the square root are what can be referred to as a discriminant. Sticking solely with the quadratic form ax^2 + bx + c = 0, the equation which allows us to solve for x is:

Here, our discriminant is b^2 - 4ac. This is what you are computing as Math.Sqrt(bPow - ac).

The discriminant, calculated on its own, allows us to deduce a few things about the solution(s) to our equation:

  • If the discriminant is zero, then there is a single solution to the quadratic.
  • If the discriminant is positive, then there are two real values of x which solve the quadratic.
  • If the discriminant is negative, then there are two complex values of x which solve the quadratic.

The discriminant in our case is 3^2 - (4 x 2 x 4), or -23, so we have no real solutions to the quadratic.

If we solve the quadratic here manually, we can calculate the two complex roots of your chosen quadratic.

If you want a challenge, C# can handle complex numbers. Alternatively, if you only want to deal with solving for real roots, you can add a check of whether the discriminant is greater-than-or-equal to zero before proceeding.


A simple way of looking at it is:

Any real number multiplied by itself will be a positive number:

a x a = a^2
2 x 2 = 2^2 = 4

-a x -a = (-a)^2
-2 x -2 = (-2)^2 = 4

Math.Sqrt(4) = 2