Answer to Question #323024 in C++ for Joyboy

Question #323024

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);


1
Expert's answer
2022-04-03T13:43:48-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS