Search code examples
c#mathconsole

c# "not a number" in console


when I try to get the value of x1 and x2, the console tells me that x1 is not a number and x2 is ?

here is the code:

static void Main(string[] args)
{
    long a, b, c;
    double x1, x2, D;
    Console.WriteLine("Write the numbers a, b, c: ");
    string[] names = Console.ReadLine().Split(" ");
    a = long.Parse(names[0]);
    b = long.Parse(names[1]);
    c = long.Parse(names[2]);
    try
    {

        D = Math.Pow(b, 2) - 4 * a * c;
        if (D > 0)
        {
            x1 = (-b + Math.Sqrt(D)) / (2.0 * a);
            x2 = (-b - Math.Sqrt(D)) / (2.0 * a);
            Console.WriteLine($"x1 = {x1}, x2 = {x2}");
        }
        if (D == 0)
        {
            x1 = (-b) / (2 * a);
            if (a != 0)
            {
                Console.WriteLine($"x1 = x2 = {x1}");
            }
            if (a == 0) { Console.WriteLine($"x = {x1}"); }
        }
        if (D < 0)
        {
            Console.WriteLine("there are no roots");
        }
    }
    catch
    {
        if (a == 0 && b == 0 && c == 0)
        {
            Console.WriteLine("x - any number");
        }

        else
        {
            Console.WriteLine("there are no solutions");
        }
    }
}

I changed the data type of x1 and x2, which led to the fact that the cat began to write to me "there are no solutions" (on catch line) i used numbers 0 1 0 and 0 1 2


Solution

  • With your data 0 1 0 you get D = 1. Therefore you enter the branch with the condition D > 0. Trying to evaluate x1 and x2 you are dividing by your variable a which is zero. The result is NaN. With your data set 0 1 2 it's quite the same: D = 1, a = 0 resulting in NaNs for x1 an x2.