Write a function in C++ to calculate and return the roots of a quadratic equation ax2 + bx + c = 0.
Return x1 and x2 through
parameter of the function. The prototype of this function is defined by:
void solveEquation(int a, int b, int c, float *x1, float *x2);
#include<iostream>
#include<string>
using namespace std;
void solveEquation(int a, int b, int c, float *x1, float *x2)
{
double discr = b*b - 4 * a*c;
if (discr > 0)
{
*x1 = (-b + sqrt(discr)) / (2 * a);
*x2 = (-b - sqrt(discr)) / (2 * a);
cout << "Quadric equation has real and different roots:\n";
}
else if (discr == 0)
{
*x1=*x2 = -b / (2 * a);
cout << "Quadric equation has real and equal roots:\n";
}
else
{
cout << "Quadric equation has complex and different roots:\n";
*x1 = -b / (2 * a);
*x2 = sqrt(-discr) / (2 * a);
}
}
int main()
{
double a, b, c;
float *x1=new float;
float *x2=new float;
cout << "Please, enter a, b, c factors for a quadric equation: ";
cin >> a >> b >> c;
solveEquation(a, b, c, x1, x2);
cout << "\nRoot1 = " << *x1
<< "\nRoot2 = " << *x2;
}
Comments
Leave a comment