-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuadratic.cpp
106 lines (91 loc) · 2.51 KB
/
Quadratic.cpp
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
103
104
105
106
/*
* File: Quadratic.cpp
* -------------------
* This program finds roots of the quadratic equation:
*
* 2
* a x + b x + c = 0
*
* If a is 0 or if the equation has no real roots, the
* program prints an error message and exits.
*/
#include <iostream>
#include <cstdlib>
#include <cmath>
#include "error.h"
/* Function prototypes */
void getCoefficients (double & a, double & b, double & c);
void solveQuadratic (double a, double b, double c,
double & x1, double & x2);
void printRoots (double x1, double x2);
//void error (const char* msg);
/* Main program */
int main()
{
double a, b, c, r1, r2;
getCoefficients (a, b, c);
solveQuadratic (a, b, c, r1, r2);
printRoots (r1, r2);
return (0);
}
/*
* Function: getCoefficients
* Usage: getCoefficients(a, b, c);
* --------------------------------
* Reads in the coefficients of a quadratic equation into the
* reference parameters a, b, and c.
*/
void getCoefficients (double & a, double & b, double & c)
{
std::cout << "Enter coefficients for the quadratic equation:" << std::endl;
std::cout << "a: ";
std::cin >> a;
std::cout << "b: ";
std::cin >> b;
std::cout << "c: ";
std::cin >> c;
}
/*
* Function: solveQuadratic
* Usage: solveQuadratic(a, b, c, x1, x2);
* ---------------------------------------
* Solves a quadratic equation for the coefficients a, b, and c. The
* roots are returned in the reference parameters x1 and x2.
*/
void solveQuadratic (double a, double b, double c,
double & x1, double & x2)
{
if (a == 0) error ("The coefficient a must be nonzero.");
double disc = b * b - 4 * a * c;
if (disc < 0) error ("This equation has no real roots.");
double sqrtDisc = sqrt(disc);
x1 = (-b + sqrtDisc) / (2 * a);
x2 = (-b - sqrtDisc) / (2 * a);
}
/*
* Function: printRoots
* Usage: printRoots(x1, x2);
* --------------------------
* Display x1 and x2, which are the roots of the quadratic equation.
*/
void printRoots (double x1, double x2)
{
if (x1 == x2)
std::cout << "There is a double root at " << x1 << std::endl;
else
std::cout << "The roots are " << x1 << " and " << x2 << std::endl;
}
/*
* Function: error
* Usage: error(msg);
* ------------------
* Writes the string msg to the cerr stream and then exits the program
* with a standard status value indicating that a failure has occurred.
*/
/*
void error (const char *msg)
{
std::cerr << msg << std::endl;
exit(EXIT_FAILURE);
}
*/