Reputation: 11
I've got a very simple little program to solve quadratic equations, in the main it works but for some reason it won't calculate square roots. I just get an error saying NaN
but I can't see how it's not a number?
int a = Convert.ToInt16(txta.Text);
int b = Convert.ToInt16(txtb.Text);
int c = Convert.ToInt16(txtc.Text);
listBox1.Items.Add(Convert.ToString(Math.Sqrt(((b * b) - (4 * a * c)))));
Upvotes: 0
Views: 532
Reputation: 20504
The conversions aren't the cause because if they didn't convert properly or if there was an overflow you'd get a FormatException
or OverflowException
respectively. None the less, since you're doing math you might want to convert to double types.
double a = Convert.ToDouble(txta.Text);
double b = Convert.ToDouble(txtb.Text);
double c = Convert.ToDouble(txtc.Text);
I believe your expression: (b * b) - (4 * a * c)
is the problem. If it evaluates to a negative number, that will result in a NaN
result.
See Math.Sqrt Method on MSDN for more information.
Upvotes: 3
Reputation: 542
It's likely getting a negative number. It might help to convert it to a double instead of an Int16, because Int16 will round every time.
Upvotes: 0