6. C++ Program to calculate roots of quadratic equation ax^2+bx+c=0

#include<iostream>
#include<cmath>
using namespace std;
// x=(-b±√(b^2-4ac))/2a
/*
where (b^2-4ac) is the discriminant.

If the value of the discriminant is zero then the equation has a single real root.
If the value of the discriminant is positive then the equation has two real roots.
If the value of the discriminant is negative, then the equation has two complex roots.

*/
int main() {

    float a, b, c, num1, num2, determinant, real, imaginary;
    cout<<"Enter coefficients a, b and c: ";
    cin >> a >> b >> c;
    determinant = b*b - 4*a*c;

    if (determinant > 0) {
        num1 = (-b + sqrt(determinant))/(2*a);
        num2 = (-b - sqrt(determinant))/(2*a);
        cout<<"Roots are real and different."<<endl;
        cout<<"num1 = "<<num1<<endl;
        cout<<"num2 = "<lt;num2<<endl;
    }

    else if (determinant == 0) {
        cout<<"Roots are real and same."<<endl;
        num1 = (-b + sqrt(determinant)) / (2*a);
        cout<<"num1 = num2 ="<<num1<<endl;
    }

    else {
        real = -b/(2*a);
        imaginary =sqrt(-determinant)/(2*a);
        cout<<"Roots are complex and different."<<endl;
        cout<<"num1 = "<<real<<"+"<<imaginary<<"i"<<endl;
        cout<<"num2 = "<<real<<"-"<<imaginary<<"i"<<endl;
    }

    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s