GMTPB
GMTPB

Reputation: 21

How to write a quadratic equation solver? (C#)

I am trying to create a simple quadratic equation (x^2 + px + q = 0) solver but the answer I get is always wrong. My code looks like this

double p, q;

Console.Write("Insert the value of p: ");
int p = int.Parse(Console.ReadLine());

Console.Write("Insert the value of q: ");
int q = int.Parse(Console.ReadLine());

Console.WriteLine("x1 = " + (-p/2 + Math.Sqrt((p/2) ^ 2 - q )));
Console.WriteLine("x2 = " + (-p/2 - Math.Sqrt((p/2) ^ 2 - q)));

My guess is that there is something wrong with the "x1 = " + (-p/2 + Math.Sqrt((p/2) ^ 2 - q ))); and the x2 = + (-p/2 - Math.Sqrt((p/2) ^ 2 - q))); parts.

Any help would be greatly appreciated.

Upvotes: 0

Views: 953

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

My guess is that there is something wrong with the x1 = ... and the x2 = ... parts.

Here is what's wrong with them:

  • Both p and q are int; they should be double, otherwise division by 2 would truncate the result.
  • n ^ 2 does not mean "squared" in C#. Use Math.Power(x, 2) instead
  • You can keep int.Parse or change to double.Parse if you would like to allow fractional input for p and q.
  • You never check that p is positive. This is required to ensure that the square root is defined.

Upvotes: 1

George_E -old
George_E -old

Reputation: 188

ax^2 + bx + c = 0

The formula for quadratics is:

(-b ± sqrt(b^2 - 4*a*c)) / 2a

So since your x^2 has no number in front, you can simplify to:

(-b ± sqrt(b^2 - 4*c)) / 2

So for you:

(-p/2 ± sqrt(p^2 - 4*q)) / 2

Upvotes: 0

Related Questions