Search This Blog

Sunday 1 May 2016

Write a C++ Program to solve quadratic equation. Raise exception when roots are not real.

Practical - 40

#include <iostream>
#include <cmath>
using namespace std;

int main() {

    float a, b, c, x1, x2, d;
    cout << "Enter coefficients a, b and c: ";
    cin >> a >> b >> c;

    try{
    d = b*b - 4*a*c;

    if (d > 0) {
        x1 = (-b + sqrt(d)) / (2*a);
        x2 = (-b - sqrt(d)) / (2*a);
        cout << "Roots are real and different." << endl;
        cout << "x1 = " << x1 << endl;
        cout << "x2 = " << x2 << endl;
    }

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

    else {
            throw "\nRoots are not real";
    }
    }catch(char const *c)
    {
        cout<<c;
    }

    return 0;
}

Output:
Enter co -eff : 3
-4
10

roots are not real

No comments:

Post a Comment