Problem 2: Solving a quadratic equation 1) Write a program in C++ that takes int
ID: 3587025 • Letter: P
Question
Explanation / Answer
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, c, X1, X2, D, real, imaginary; // D stands for Discriminant
cout << "Enter coefficient a: ";
cin >> a;
cout << "Enter coefficient b: ";
cin >> b;
cout << "Enter coefficient c: ";
cin >> c;
cout << a <<"x2 + " << b <<"x + " <<c << " = 0"; // 1) Printing the equation
D = b*b - 4*a*c; // 2) code to calculate D
if (D == 0) // 3(a) when D=0
{
cout << "The Equation has double solution : " << endl;
X1 = -b / (2*a);
cout << "X1 = X2 =" << X1 << endl;
}
else if (D > 0) // 3(b) when D>0
{
X1 = (-b + sqrt(D)) / (2*a);
X2 = (-b - sqrt(D)) / (2*a);
cout << "It has two different solutions :" << endl;
cout << "X1 = " << X1 << endl;
cout << "X2 = " << X2 << endl;
}
else // 3(c) when D<0
{
real = -b/(2*a);
imaginary =sqrt(-D)/(2*a);
cout << "The equation has no real solution." << endl;
cout << "X1 = " << real << "+" << imaginary << "i" << endl;
cout << "X2 = " << real << "-" << imaginary<< "i" << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.