Can someone just help me get started with this. I believe I need to break this into two functions? one called x1 and another called x2? then have the calculations inside the functions rather than being in main? here are my instructions listen below. Then I posted the code as well. Thank you for your time and help.
This version uses smart numerical analysis techniques to find more accurate
solutions in cases where a straightforward use of the quadratic formula
would not work or would not give very accurate answers (because of
"catastrophic cancellation"). There are two techniques used: the coefficients
are first normalized. Then, in cases where there are 2 solutions, only one
solution, call it x1, is calculated using the quadratic formula, namely the
solution in which cancellation cannot occur. Then the second solution, call it
x2, is calculated using x2 = c / (a * x1).
*/
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
#include <iostream>
#include <cmath> // Needed for the sqrt function.
using namespace std;
int main(void)
{
char Reply;
int NumSolutions;
float a, b, c, ANorm, BNorm, CNorm, x1, x2, Discriminant, Root, Largest;
do
{
cout << "Quadratic Equation Solver" << endl << endl;
cout << "Enter the value of coefficient a: ";
cin >> a;
cout << "Enter the value of coefficient b: ";
cin >> b;
cout << "Enter the value of coefficient c: ";
cin >> c;
if (fabs(a) > fabs(b))
Largest = fabs(a);
else
Largest = fabs(b);
if (fabs(c) > Largest)
Largest = fabs(c);
ANorm = a / Largest;
BNorm = b / Largest;
CNorm = c / Largest;
Discriminant = BNorm * BNorm - 4.0f * ANorm * CNorm;
if (Discriminant < 0)
NumSolutions = 0;
else if (Discriminant == 0)
{
NumSolutions= 1;
x1 = -BNorm / (2.0f * ANorm);
}
else // Discriminant must be positive
{
NumSolutions = 2;
Root = sqrt(Discriminant);
if (-BNorm > 0)
x1 = (-BNorm + Root) / (2.0f * ANorm);
else
x1 = (-BNorm - Root) / (2.0f * ANorm);
x2 = CNorm / (ANorm * x1);
}
if (NumSolutions == 0)
cout << "No real solutions" << endl;
else if (NumSolutions == 1)
cout << "One real solution: " << x1 << endl;
else
cout << "Two real solutions: " << x1 << " and " << x2 << endl;
cout << "Solve another (y/n)? ";
cin >> Reply;
} while (Reply == 'y');
return 0;
}
|