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 97 98 99 100 101 102
|
#include <iostream>
#include <cmath>
using namespace std;
inline void normalize(float & a,float & b,float & c);
void solution(float a, float b, float c, int & NumSolutions, float & x1, float & x2);
void input(float & a, float & b, float & c);
inline float Discriminant(float a, float b, float c);
void PrintSolutions(int NumSolutions, float x1, float x2);
int main(void)
{
char Reply;
float a, b, c, x1, x2;
int NumSolutions;
do
{
cout << "Quadratic Equation Solver" << endl << endl;
input(a, b, c);
solution(a, b, c, NumSolutions, x1, x2);
PrintSolutions(NumSolutions, x1, x2);
cout << "Solve another (y/n)? ";
cin >> Reply;
}
while (Reply == 'y');
}
void input(float & a, float & b, float & c)
{
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)
{
float Largest;
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;
}
float Discriminant(float a, float b, float c)
{
return pow(b, 2) - 4.0f * a * c;
}
void solution(float a, float b, float c, int & NumSolutions, float & x1, float & x2)
{
float discrim, Root;
normalize(a, b, c);
discrim = Discriminant(a, b, c);
if (discrim < 0)
NumSolutions = 0;
else if (discrim == 0)
{
x1 = -b / (2.0f * a);
NumSolutions = 1;
}
else // Discriminant must be positive
{
Root = sqrt(discrim);
NumSolutions = 2;
if (-b > 0)
x1 = (-b + Root) / (2.0f * a);
else
x1 = (-b- Root) / (2.0f * a);
x2 = c / (a * x1);
}
}
void PrintSolutions(int NumSolutions, float x1, float x2)
{
if (NumSolutions == 0)
cout << "No real solutions" << endl;
else if (NumSolutions == 1)
cout << "One real solution: " << "x1:" << x1 << endl;
else
cout << "Two real solutions: " << "x1:" << x1 << " and " << "x2:" << x2 << endl;
}
|