In: Computer Science
Write a C++ program that solves a quadratic equation to find its roots. The roots of a quadratic equation ax2 + bx + c = 0 (where a is not zero) are given by the formula (–b ± sqrt(b2 – 4ac)) / 2a *Use #include for the use of sqrt. The value of the discriminant (b2 – 4ac) determines the nature of roots. If the value of the discriminant is zero, then the equation has a single real root. If the value of the discriminant is positive then the equation has two real roots. If the value of the discriminant is negative, then the equation has two complex roots. The program takes values of a, b, and c as input and outputs the roots. Be creative in how you output complex roots. Include a loop that allows the user to repeat this calculation for new input values until the user says she or he wants to end the program.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
void calculate();
int main(){
while(1){
calculate();
char opt[2];
cout << "Do you want to continue - (y/n) :";
cin >> opt;
if(opt[0] == 'n')
break;
}
return 1;
}
void calculate(){
int a, b, c;
cout << "Equation : ax^2 + bx +c = 0" <<endl;
cout << "a = ";cin >> a;
cout << "b = ";cin >> b;
cout << "c = ";cin >> c;
// calculating discriminant
double discriminant = b*b - 4*a*c;
// checking type of root
// real root
// single root
// imaginary root
if(discriminant > 0){
double sqrtD = sqrt(discriminant);
// calculating roots
double root1 = (-b + sqrtD)/(2*a);
double root2 = (-b - sqrtD)/(2*a);
// printing roots
cout << "Root 1 : " << root1 <<endl;
cout << "Root 2 : " << root2 <<endl;
}else if(discriminant == 0){
// calculating root
double root = -b/(2*a);
// printing root
cout <<"Root : " << root <<endl;
}else if(discriminant < 0){
discriminant = sqrt(abs(discriminant));
string root1 = "( "+to_string(-b)+" + "+to_string(discriminant)+"i ) / "+to_string(2*a);
string root2 = "( "+to_string(-b)+" - "+to_string(discriminant)+"i ) / "+to_string(2*a);
cout << root1 <<endl;
cout << "Root 1 : " << root1 <<endl;
cout << "Root 2 : " << root2 <<endl;
}
}
Code
Output