Write a function 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 <cmath>
using namespace std;
void solveEquation(int a, int b, int c, float *x1, float *x2)
{
double d = b*b - 4*a*c;
if (d < 0) {
cout << "Equation does not have real roots" << endl;
return;
}
*x1 = (-b + sqrt(d)) / (2*a);
*x2 = (-b - sqrt(d)) / (2*a);
}
int main() {
int a, b, c;
float x1, x2;
cout << "Enter coefficients a, b, c: ";
cin >> a >> b >> c;
solveEquation(a, b, c, &x1, &x2);
cout << "The roots are " << x1 << " and " << x2 << endl;
return 0;
}
Comments
Leave a comment