I'm working on a problem that says to write a program that accepts from the keyboard 3 numbers a, b, c which are the coefficients of the quadratic equation ax^2 +bx+c=0. Then, to make sure that:
1. b^2-4ac >=0
2. a does not equal zero
3. b^2 is not significantly > 4ac.
or else the program stops.
Otherwise, it outputs the real roots of the quadratic equation. I have, I believe, a program that does that just fine. However, another requirement is that there be absolutely minimal computations. Specificially, "division by 2a twice is allowable, otherwise none." I can't figure out how to possibly do that. Maybe a switch function? Anyway, here's the program I have that does the basics of the problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double a, b, c, root1, root2;
root1 = (-b +sqrt(( pow (b,2) - 4*a*c )))/2*a;
root2 = (-b - sqrt(( pow (b,2) - 4*a*c )))/2*a;
cout << "Enter the three coefficients: a, b, and c.\n";
cin >> a >> b >> c;
if ((b*b - 4*a*c < 0))
{
cout<< "Invalid, b*b - 4ac MUST be >= 0.\n";
return 0;
}
else
if (a == 0)
{
cout<< "Invalid, 'a' cannot equal zero.\n";
return 0;
}
else
if ((b*b > 10*4*a*c))
{
cout<< "Invalid, 'b' variable too large.\n";
return 0;
}
else
cout<< "root1 = " << root1 << endl;
cout<< "root2 = " << root2 << endl;
return 0;
}
|
Any help is welcome, thanks