Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS151 / KCS251 Programming for Problem Solving - Using C Language
Lab Exercises
3. Write a program to determine the roots of a quadratic equation.
/*
File: Prgrm03.c
Author: Aditya Saini
Date: Jan 15, 2021
Description: Program to determine the roots of a quadratic equation.
*/
#include <stdio.h>
#include <math.h>
int main (void)
{
double a, b, c;
double dis;
double root_1, root_2, real, img;
//Input a, b and c for eq. ax2+bx+c = 0.
printf ("For eq. ax^2 + bx + c = 0\n");
printf ("Input a: ");
scanf ("%lf", &a);
printf ("Input b: ");
scanf ("%lf", &b);
printf ("Input c: ");
scanf ("%lf", &c);
//Calculate discriminant = b2-4ac
dis = b * b - 4 * a * c;
//If roots are real and different
if (dis > 0)
{
root_1 = (-b + sqrt (dis)) / (2 * a);
root_2 = (-b - sqrt (dis)) / (2 * a);
printf ("First Root = %.2lf\n", root_1);
printf ("Second Root = %.2lf", root_2);
}
//If roots are real and equal
else if (dis == 0)
{
root_1 = root_2 = -b / (2 * a);
printf ("First Root = Second Root = %.2lf", root_1);
}
//If roots are imaginary
else
{
real = -b / (2 * a);
img = sqrt (-dis) / (2 * a);
printf ("First Root = %.2lf + %.2lfi\n", real, img);
printf ("Second Root = %.2lf - %.2lfi", real, img);
}
return 0;
};
Output
For eq. ax^2 + bx + c = 0
Input a: 1
Input b: 2
Input c: 3
First Root = -1.00 + 1.41i
Second Root = -1.00 - 1.41i
No comments:
Post a Comment
Please do not post spam links.