private void btnCompute_Click(object sender, EventArgs e)
{
double coefficientA;
double coefficientB;
double coefficientC;
double root1;
double root2;
double discriminant;
coefficientA = double.Parse(txtCoeA.Text);
coefficientB = double.Parse(txtCoeB.Text);
coefficientC = double.Parse(txtCoeC.Text);
discriminant =
(coefficientB * coefficientB) -
(4 * coefficientA * coefficientC);
txtOutput.Text = "Discriminant = " + discriminant.ToString("N2");
//-b/2a
root1 = (-coefficientB + discriminant) / (2 * coefficientA);
root2 = (-coefficientB - discriminant) / (2 * coefficientA);
if (discriminant < 0)
{
txtOutput.Text += "\r\nEquation has no real roots!";
}
else if (discriminant == 0)
{
txtOutput.Text +=
"\r\nEquation has one root: " + root2.ToString("N2");
}
else if (discriminant > 0)
{
txtOutput.Text = "Equation has two real roots: " +
"\r\nroot1: " +
(-coefficientB + Math.Sqrt(discriminant) /
(2 * coefficientA)) +
"\r\nroot2: " + (coefficientB - Math.Sqrt(discriminant) /
(2 * coefficientA));
}
}
Asked
Active
Viewed 472 times
-3

Shaun Luttin
- 133,272
- 81
- 405
- 467

Samantha
- 3
- 2
-
Quadratic roots, not square roots. – Martin James Feb 16 '15 at 00:54
-
Also, should you not be taking the square root of the discriminant? – Martin James Feb 16 '15 at 00:56
-
Is it not? Math.Sqrt(discriminant) takes care of that doesn't it? – Samantha Feb 16 '15 at 01:00
-
There is mistakes in parenthesis, roots are `(-coefficientB + Math.Sqrt(discriminant)) / (2 * coefficientA)` and `(-coefficientB - Math.Sqrt(discriminant)) / (2 * coefficientA)` – mpromonet Feb 16 '15 at 01:00
-
What is your method trying to achieve? – Shaun Luttin Feb 16 '15 at 01:05
-
Oh my gosh! How dumb of me. Thank you so much! That fixes it completely. – Samantha Feb 16 '15 at 01:06
1 Answers
0
Try this:
txtOutput.Text = "Equation has two real roots: " +
"\r\nroot1: " +
(-coefficientB + Math.Sqrt(discriminant)) / (2 * coefficientA) +
"\r\nroot2: " +
(-coefficientB - Math.Sqrt(discriminant)) / (2 * coefficientA);
You were bracketing the formula incorrectly.

Enigmativity
- 113,464
- 11
- 89
- 172
-
..and, even after the edit, 'root1 = (-coefficientB + discriminant) / (2 * coefficientA);' etc. has been left in. – Martin James Feb 16 '15 at 01:06
-
-
@MartinJames - Yes, I noticed that, but he's not using `root1` or `root2` so I just decided to ignore that. – Enigmativity Feb 16 '15 at 01:07
-