﻿ C exercises and solutions: C if else logical operators (continued)

# C exercises and solutions: C if else logical operators (continued)

## C if else logical operators exercises (con.)

### 3. Write C code to compute the real roots of the equation: ax2+bx+c=0.

The program will prompt the user to input the values of a, b, and c. It then computes the real roots of the equation based on the following rules:
-if a and b are zero=> no solution
-if a is zero=>one root (-c/b)
-if b2-4ac is negative=>no roots
-Otherwise=> two roots
The roots can be computed using the following formula:
x1=-b+(b2-4ac)1/2/2a
x=-b-(b2-4ac)1/2/2a

Solution

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char *argv[])
{

float a;
float b;
float c;
float delta;
printf("Enter values of a b c separated by space:");
scanf("%f %f %f",&a,&b,&c);
if(a==0 && b==0)printf("No root");
else if(a==0)printf("The equation has only one root:%.2f",-b/c);
else {
delta=b*b-4*a*c;
if(delta<0) printf("No root");
else printf("The equation has two roots:x=%.2f",-b+sqrt(b*b-4*a*c)/(2*a));printf(",x1=%.2f",-b-sqrt(b*b-4*a*c)/(2*a));
}

printf("\n");

system("PAUSE");
return 0;

}