Hello all,
I'm trying to write a program that will compute the real roots of the quadratic equation ax^2 + bx + c = 0 given by:
x1 = (- b + sqrt (b^2 - 4ac)) / 2a and x2 = (- b - sqrt (b^2 - 4ac)) / 2a.
Based on the values of "a", "b", and "c" entered by a user, the roots will be calculated based on the following set of rules:
1. if a and b are zero, there are no solutions.
2. if a is zero, then there in one real root (-c / b).
3. if the discriminate (sqrt(b^2 - 4ac)) is negative, then there are no real roots.
4. for all other combinations, there are two real roots.
I figured I could accomplish this with a series of "if" statements....no else statements....
The code I came up with is as follows:
int main()
{
float a;
float b;
float c;
float x1;
float x2;
float one_root;
printf("Please enter value for a:");
scanf("%f", &a);
printf("Please enter value for b:");
scanf("%f", &b);
printf("Please enter value for c:");
scanf("%f", &c);
if (a == 0 && b ==0)
{
printf("There are no solutions.");
}
if (a == 0)
{
one root = -c / b;
printf("There is one root of %f.);
}
if (sqrt(pow (b ,2)) - (4 * a * c)) < 0)
{
printf("There are no real roots.");
}
if (a < 0 && a > 0 && b < 0 && b > 0)
{
x1 = (-b + sqrt ((pow (b, 2)) - (4 * a * c))) / (2 * a);
x2 = (-b + sqrt ((pow (b, 2)) - (4 * a * c))) / (2 * a);
printf("The two real roots are %f and %f.", x1, x2);
}
return 0;
}
I haven't had a chance to try it to see if it works because I can't get to a computer with software that will let me do it right now. What I really want to know right now is that it's ok to write the code just using "if" statements and leaving out the "else".
Thanks