Modify the given Program so that it will calculate all possible roots of quadrat
ID: 675298 • Letter: M
Question
Modify the given Program so that it will calculate all possible roots of quadratic equation(include Imaginary number)
#include<iostream.h>
#include<math.h>
//this program solves for the roots of a quadratic equation
int main()
{
double a, b, c, disc, root1, root2;
cout<< "this program calculates the roots of a ";
cout<< " quadratic equation of the form ";
cout<< " 2/n";
cout<< " ax+bx+c=0 ";
cout<< "please enter values for a, b, and c: ";
cin>> a >> b>> c;
if ( a ==0.0 && b == 0.0)
cout<< "The equation is degenerate and has no roots. ";
else if (a==0.0)
cout << "The equation has the single root x = "
<< -c/b << endl
else
{
disc = pow(b,2.0) - 4*a*c; //calculate discriminant
if (disc> 0.0)
{
disc = sqrt(disc);
root1=(-b+disc)/(2*a);
root2=(-b-disc)/(2*a);
cout<< "The two real roots are"
<< root1 << "and" << root2 << endl;
}
else if (disc<0.0)
cout<< "Both roots are imaginary. ";
else
cout<<"Both roots are equal to " <<-b/(2*a)<<endl;
}
return 0;
}
Explanation / Answer
#include<iostream>
#include<math.h>
using namespace std;
//this program solves for the roots of a quadratic equation
int main()
{
double a, b, c, disc, root1, root2;
cout<< "this program calculates the roots of a ";
cout<< " quadratic equation of the form ";
cout<< " 2/n";
cout<< " ax+bx+c=0 ";
cout<< "please enter values for a, b, and c: ";
cin>> a >> b>> c;
if ( a ==0.0 && b == 0.0)
cout<< "The equation is degenerate and has no roots. ";
else if (a==0.0)
cout << "The equation has the single root x = "<< -c/b << endl;
else
{
disc = pow(b,2.0) - 4*a*c; //calculate discriminant
if (disc> 0.0)
{
disc = sqrt(disc);
root1=(-b+disc)/(2*a);
root2=(-b-disc)/(2*a);
cout<< "The two real roots are"
<< root1 << "and" << root2 << endl;
}
else if (disc<0.0) {
cout<< "Both roots are imaginary. ";
double realPart = -b/(2*a);
double imaginaryPart =sqrt(-disc)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
}
else
cout<<"Both roots are equal to " <<-b/(2*a)<<endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.