151: The roots of the quadratic equation ax2 + bx + c = 0, a≠ 0 are given by the following formula: // x = -b ± √(b2 - 4ac) / 2a //In this formula, the term b2 - 4ac is called the discriminant. If b2 - 4ac = 0, then the equation has a single (repeated) root. If b2- 4ac > 0, the equation has two real roots. If b2-4ac < 0, the equation has two complex roots. Write a program that prompts the user to input the value of a (the coefficient of x2 ), b (the coefficient of x), and c (the constant term) and outputs the type of roots of the equation. Furthermore, if b2-4ac = 0, the program should output the roots of the quadratic equation
// The roots of the quadratic equation ax2 + bx + c = 0, a≠ 0 are given by the following formula:
// x = -b ± √(b2 - 4ac) / 2a
// In this formula, the term b2 - 4ac is called the discriminant. If b2 - 4ac = 0, then the equation has
// a single (repeated) root. If b2- 4ac > 0, the equation has two real roots. If b2-4ac < 0, the equation
// has two complex roots. Write a program that prompts the user to input the value of a (the coefficient
// of x2 ), b (the coefficient of x), and c (the constant term) and outputs the type of roots of the
// equation. Furthermore, if b2-4ac = 0,
// the program should output the roots of the quadratic equation
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << "Muhammad Umar Chaudhry" << endl;
cout << "SU92-BSCSM-S23-007" << endl;
cout << "Question # 9" << endl
<< endl;
double a, b, c;
cout << "Enter the value of b: ";
cin >> b;
cout << "Enter the value of a: ";
cin >> a;
cout << "Enter the value of c: ";
cin >> c;
double discriminant = (b * b) - (4 * a * c);
if (discriminant == 0)
{
cout << "The equation has a single root" << endl;
cout << "x = " << -b / 2 * a << endl;
}
else if (discriminant > 0)
{
cout << "The equation has two real roots" << endl;
cout << "x1 = " << (-b + sqrt(discriminant)) / 2 * a << endl;
cout << "x2 = " << (-b - sqrt(discriminant)) / 2 * a << endl;
}
else if (discriminant < 0)
{
cout << "The equation has two complex roots" << endl;
cout << "x1: \nReal part = " << -b / 2 * a << endl
<< "Imaginary part: " << 1 * sqrt(-1 * discriminant) << 'i' << endl
<< endl;
cout << "x2: \nReal part = " << -b / 2 * a << endl
<< "Imaginary part: " << -1 * sqrt(-1 * discriminant) << 'i' << endl
<< endl;
}
return 0;
}
Comments
Post a Comment