0

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.

GMTPB
  • 21
  • 3

2 Answers2

1

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.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

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
George_E -old
  • 188
  • 1
  • 3
  • 17