Search code examples
cquadratic

Program returns incorrect answer and "-nan(ind)". What did I do wrong?


This is my code

#include <stdio.h>
#include <math.h>
void main()
{
float a = 0, b = 0, c = 0;
float disc = b*b - 4 * a*c;
float sing = -b / (2 * a);
float lin = -c / b;
float quad1 = (-b + (disc)) / (2 * a);
float quad2 = (-b - (disc)) / (2 * a);
printf_s("Please enter the coefficients a, b, and c\n");
scanf_s("%g %g %g", &a, &b, &c);
if (a == 0)
{
    if (b == 0)
    {
        if (c == 0)
        {
            printf_s("There are infinite solutions\n");
        }
        else
        {
            printf_s("There is no solution\n");
        }
    }
    else
    {
        printf_s("The singular solution is %g\n", lin);
    }
}
else
{
    if (disc < 0)
    {
        printf_s("There is no real solution\n");
    }
    else 
    {
        if (disc == 0)
        {
            printf_s("The singular solution is %g\n", sing);
        }
        else
        {
            printf_s("The solutions are x1 = %g and x2 = %g\n", quad1, quad2);
            }
        }
    }
}

I'm trying to build a quadratic formula calculator. When I plug in a = 2, b = 1, and c = -21, I expect to receive x = 3 and x = -3.5 But instead I get the output "The singular solution is -nan(ind)" What does this mean? How do I fix it?


Solution

  • You're calculating the value of disc before input. Change the order.

    That also goes for sing, lin, quad1 and quad2.

    float a, b, c;
    printf_s("Please enter the coefficients a, b, and c\n");
    scanf_s("%g %g %g", &a, &b, &c);
    float disc = b*b - 4 * a*c;
    float sing = -b / (2 * a);
    float lin = -c / b;
    float quad1 = (-b + (disc)) / (2 * a);
    float quad2 = (-b - (disc)) / (2 * a);