-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathquadratic.cpp
More file actions
61 lines (52 loc) · 1.4 KB
/
quadratic.cpp
File metadata and controls
61 lines (52 loc) · 1.4 KB
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
#include <stdexcept>
#include <cmath>
#include <iomanip>
#include <iostream>
bool isLevelLine(int a, int b) {
return a == 0 && b == 0;
}
bool isLinear(int a, int b){
if (a == 0 && b != 0) return true;
else return false;
}
bool isQuadratic(int a){
if (a != 0) return true;
else return false;
}
std::string AddRootToStr(double x){
std::ostringstream oss;
oss << std::setprecision(6);
if (std::abs(x - std::round(x)) < 1e-10) {
oss << static_cast<int>(std::round(x));
} else {
oss << x;
}
return oss.str();
}
void SolveQuadratic(int a, int b, int c) {
std::string result = "";
if (isLevelLine(a, b)){
result = (c == 0) ? "infinite solutions" : "no solutions";
}
else if (isLinear(a, b)){
double x = -static_cast<double>(c) / b;
result = AddRootToStr(x);
}
else if (isQuadratic(a)){
double discr = b * b - 4 * a * c;
if (discr < 0) {
result = "no solutions";
}
else if (std::abs(discr) < 1e-10) {
double x = -b / (2.0 * a);
result = AddRootToStr(x);
}
else {
double x1 = (-b + sqrt(discr)) / (2.0 * a);
double x2 = (-b - sqrt(discr)) / (2.0 * a);
if (x1 > x2) std::swap(x1, x2);
result = AddRootToStr(x1) + " " + AddRootToStr(x2);
}
}
std::cout << result;
}