-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoly2complex.cc
More file actions
39 lines (37 loc) · 1.32 KB
/
poly2complex.cc
File metadata and controls
39 lines (37 loc) · 1.32 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
/*
* compile with GNU compiler collection 3.6.+:
* g++ -o poly2complex poly2complex.cc
*/
#include <string>
#include <iostream>
#include <math.h>
#include <complex>
int main(int argc, char *argv[]) {
// print warning and usage help if not enough arguments given
if(argc < 4) {
std::cout << "run " << argv[0] << " with 3 line options: a, b and c" << std::endl;
std::cout << "e.g." << std::endl;
std::cout << argv[0] << " 1 -5 6" << std::endl;
return -1;
}
double a, b, c;
// complex field will be used to solve eq.
std::complex<double> discriminant, root_discriminant, x1, x2;
// convert lineopts string arguments to doubles
a = std::stod(argv[1]);
b = std::stod(argv[2]);
c = std::stod(argv[3]);
// find discriminant
discriminant = b * b - 4.0 * a * c;
std::cout << "equation " << std::endl << a << "x^2 + " << b << "x + " << c << " = 0" << std::endl;
if(discriminant == 0.0) { // 2-multiple root
x1 = -b / (2.0 * a);
std::cout << "has 2-multiple root x = " << x1 << std::endl;
} else {
root_discriminant = sqrt(discriminant);
x1 = (-b + root_discriminant) / (2.0 * a);
x2 = (-b - root_discriminant) / (2.0 * a);
std::cout << "has roots x1 = " << x1 << " and x2 = " << x2 << std::endl;
}
return 0;
}