Search code examples
c#equation-solving

quadratic equation solver that not work


I had create this equation solver (I know that is pretty confusing and maybe I've done stupid mistakes but I started recently), but it doesen't works. It doesn't print x1 and x2 on the console. Can you help me?

Console.WriteLine("input the coefficent a");
double a = int.Parse(Console.ReadLine());

Console.WriteLine("input the coefficent b");
double b = int.Parse(Console.ReadLine());

Console.WriteLine("input coefficent c");
double c = int.Parse(Console.ReadLine());

double D = Math.Pow(b,2) - 4*(a*c);
Console.WriteLine(D);

double x1;
double x2;

if (Convert.ToBoolean(D = 0))
{
    x1 =  Convert.ToInt32((-b)) / (2 * Convert.ToInt32(a));
    x2 = Convert.ToInt32((-b)) / (2 * Convert.ToInt32(a));
    Console.WriteLine(x1);
    Console.WriteLine(x2);

}
else if (Convert.ToBoolean(D > 0))
{
    x1 = (-b - (Math.Sqrt( Math.Pow(b,2) - 4 * a * c)) / 2 * a);
    x2 = (-b + (Math.Sqrt(Math.Pow(b,2) - 4 * a * c)) / 2 * a);
    Console.WriteLine(x1);
    Console.WriteLine(x2);
}
else if (Convert.ToBoolean(D < 0))
    Console.WriteLine("the equation has no real roots");

The output is:

input the coefficent a

1 input the coefficent b

3

input coefficent c

2

1

Premere un tasto per continuare . . .


Solution

  • if(Convert.ToBoolean(D = 0)) is not what you want. It assigns 0 to D, returns 0 and converts this to false. You want if (D == 0) as well as else if(D > 0) and else if(D < 0)

    A single = assigns to variables, == compares them.

    You also don't need to cast a condition to boolean inside an if-clause, if you need to do this you should think twice if you did something wrong.