Firstly, your data type inputs (int) are probably not what you want. Attempting to compute sqrts or divisions using integers is not going to end well. Try using double instead?
typedef struct { double m, n; } roots;
roots quadratic_formula(double a, double b, double c) {
double root1,root2;
root1 = ((-b)+sqrt((b*b)-4*a*c))/(2*a);
root2 = ((-b)-sqrt((b*b)-4*a*c))/(2*a);
return {root1, root2};
}
Now for the bigger problems.
(b*b)-4*a*c)
can be negative, in which case the quadratic does not have a solution.
typedef struct { double m, n; int has_solution; } roots;
roots quadratic_formula(double a, double b, double c) {
double root1,root2;
double discriminant = (b*b)-4.0*a*c);
if(discriminant < 0) {
return (roots) { 0, 0, 0 };
}
root1 = ((-b)+sqrt(discriminant)/(2*a);
root2 = ((-b)-sqrt(discriminant)/(2*a);
return {root1, root2, 1};
}
If a
is equal to zero, the equation is not a quadratic, and will need to be solved as a linear equation. If b
is also zero, the equation has no solution.
typedef struct { double m, n; int has_solution; } roots;
roots quadratic_formula(double a, double b, double c) {
// if linear
if(a == 0) {
if(b == 0) return {0,0,0}; // no solution
double root = -c / b;
return {root, root, 1};
}
double root1,root2;
double discriminant = (b*b)-4.0*a*c);
// quadratic is always above the y = 0 line
if(discriminant < 0) {
return (roots) { 0, 0, 0 };
}
root1 = ((-b)+sqrt(discriminant)/(2*a);
root2 = ((-b)-sqrt(discriminant)/(2*a);
return {root1, root2, 1};
}