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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <iostream>
#include <cmath>
using namespace std;
void input() ;
void normalize(float a,float b,float c) ;
void solution(float save_a,float save_c) ;
int NumSolutions;
//*** Get rid of all global variables: Largest; Put them where they are used.
int main(void)
{
char Reply;
float a, b, c; //Declare a, b, and c here where you first use them.
do
{
input(); //*** Now that a, b, c are not global, you will have to pass them as parameters. Think: what kind of parameters -- value or reference?
//*** There is no need to save the original a and c. Use the normalized versions only. Get rid of save_a, save_c.
normalize(a,b,c);
solution(a,b,c); // *** Pass a, b, and c to this function.
cout << "Solve another (y/n)? ";
cin >> Reply;
}
while (Reply == 'y');
}
void input(float & a, float & b, float & c) //*** As stated above, you need a, b, and c as parameters.
{
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;
}
void normalize(float & a, float & b, float & c) //*** Good, you have parameters here. Should they be value parameters or reference parameters?
{
float Largest;
//*** Your code to find the Largest is incorrect. Compare it to the original and put it back the way it was.
if (fabs(a) > fabs(b))
Largest = fabs(a);
else
Largest = fabs(b);
if (fabs(c) > Largest)
Largest = fabs(c);
a = a / Largest;
b = b / Largest;
c = c / Largest;
}
void solution(float & a, float & b, float & c) //*** As stated above, pass in a, b, c (the normalized versions).
{
float Discriminant, Root, x1, x2;
int NumSolutions;
Discriminant = pow(b,2) - 4.0f *a *c;
if (Discriminant < 0)
NumSolutions = 0;
else if (Discriminant == 0)
{
NumSolutions= 1;
x1 = -b / (2.0f * a);
}
else // Discriminant must be positive
{
NumSolutions = 2;
Root = sqrt(Discriminant);
if (-b > 0)
x1 = (-b + Root) / (2.0f * a);
else
x1 = (-b - Root) / (2.0f * b);
x2 = c / (a * 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;
// x2 = c / (a * x1); //*** No, use a and c. Using these saved versions defeats the purpose of normalization.
// cout << "Two real solutions: " << x1 << " and " << x2 << endl;
}
|