Sunday 15 June 2014

C++ program to find the roots of a quadratic equation

 
C++ program to find the roots of a quadratic equation. First program is to show the main logic behind the program and second program is to show how we can implement it using class.


C++ program to find the roots of a quadratic equation

#include <math.h>
#include<iostream>
using namespace std;
int main()
{
    int a,b,c;
    float root1,root2;
    cout<<"Enter the coefficient of x^2 ";
    cin>>a;
    cout<<"Enter the coefficient of x ";
    cin>>b;
    cout<<"Enter the value of constant ";
    cin>>c;
    root1=((-b)+sqrt((b*b)-(4*a*c)))/(2*a);
    root2=((-b)-sqrt((b*b)-(4*a*c)))/(2*a);
    cout<<"First root "<<root1<<endl;
    cout<<"Second root "<<root2;
    return 0;
}



C++ program to find the roots of a quadratic equation using class

#include <math.h>
#include<iostream>
using namespace std;
class equation
{
private:
    float root1,root2;
    int a,b,c;
public:
    void getcof()
    {
        cout<<"Enter the coefficient of x^2 ";
        cin>>a;
        cout<<"Enter the coefficient of x ";
        cin>>b;
        cout<<"Enter the value of constant ";
        cin>>c;
    }
    void findroot()
    {
        root1=((-b)+sqrt((b*b)-(4*a*c)))/(2*a);
        root2=((-b)-sqrt((b*b)-(4*a*c)))/(2*a);
        cout<<"First root "<<root1<<endl;
        cout<<"Second root "<<root2;
    }
};
int main()
{
    equation root;
    root.getcof();
    root.findroot();
    return 0;
}

No comments:

Post a Comment