Why is my C# calculation being returned as a NaN?

206 views Asked by At

I'm doing the C# Unity course on Coursera and the first assignment is doing my head in. Yes I'm new to programming so please cut me some slack.

I'm trying to calculate the distance of the hypotenuse between two character locations.

enter image description here

I am forced to in order use 5 5 for both Y points and 4 4 for both X points.

First I calculate the deltaY by subtracting point2Y from point1Y then deltaX by doing the same for the X points.

Then, I am required to save the distance as a float, so using casting, I layout my Pythagorean theorem formula to find the distance.

BUT, I keep getting the right answer for 5 5 4 4 but when I am required to use 2 2 for the Y and 4 4 for the X I get NaN.

This is because I am getting a negative number which shouldn't be the case. Any help would be appreciated!

My Code Below

float point1X = 5;
float point1Y = 5;
float point2X = 4;
float point2Y = 4;
        
double deltaX = point2X - point1X;
double deltaY = point2Y - point1Y;

float distance = (float) (Math.Sqrt(Math.Sqrt(deltaX) + Math.Sqrt(deltaY)));
Console.WriteLine(distance);
1

There are 1 answers

0
OmG On

You need to update the definition of the distance between the two points. It is incorrect now. It should be the power 2 of the delta (instead of the square root).

float distance = (float) (Math.Sqrt(deltaX * deltaX + deltaY * deltaY));

or

float distance = (float) (Math.Sqrt(Math.Pow(deltaX, 2.0) + Math.Pow(deltaY, 2.0)));

By the way, as mentioned in the comments, the square root of negative values (that can be possible for deltaX or deltaY) is the provenance of the error that you've gotten.