Project objective: write a program that solves quadratic equations. See above fo
ID: 675224 • Letter: P
Question
Project objective: write a program that solves quadratic equations. See above for the due date.
Write a C++ program that will prompt the user for at least one polynomial that is at most a quadratic function, i.e.,
f(x) = a x2+ b x + c
where a, b, and c are real numbers, and find all its real or complex roots using (where appropriate) the quadratic formula:
x = [-b ± (b2-4ac)½] / (2a).
Use the pre-defined C++ function sqrt to evaluate the square root of a real number of data type double:
d = sqrt (disc);
where disc is the discriminant of a quadratic function. You will need the header file:
#include <cmath>
Recall that a complex number has the form:
d + fi
where d is the real part, f is the imaginary part, and
i = (–1)½.
Prompt the user for the coefficients a, b, and c. Be sure to test your program with at least the following inputs.
a = 0, b = 0, c = 0 (note: this is not a quadratic equation)
a = 0, b = 0, c = 1 (ditto)
a = 0, b = 2, c = 1 (ditto)
a = 5, b = 0, c = 0
a = 6, b = 0, c = 7
a = 8, b = 9, c = 0
a = 10, b = 11, and c = 12
a = 1.92, b = -8.37, c = 4.65
If the user input is invalid, then output an appropriate error message and exit the program.
Explanation / Answer
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, c, x1, x2, disc, realPart, imaginaryPart;
cout << "Enter coefficients a, b and c: ";
cin >> a >> b >> c;
if (a<=0)
{
cout<< "Invalid Input";
return 0;
}
disc = b*b - 4*a*c;
if (disc > 0)
{
x1 = (-b + sqrt(disc)) / (2*a);
x2 = (-b - sqrt(disc)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
else if (disc == 0)
{
cout << "Roots are real and same." << endl;
x1 = (-b + sqrt(disc)) / (2*a);
cout << "x1 = x2 =" << x1 << endl;
}
else
{
realPart = -b/(2*a);
imaginaryPart =sqrt(-disc)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.