-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0318Complex.cpp
More file actions
68 lines (66 loc) · 1.77 KB
/
0318Complex.cpp
File metadata and controls
68 lines (66 loc) · 1.77 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
62
63
64
65
66
67
68
/* solution for quadratic equation: using two classes */
#include <iostream>
#include <math.h>
#include <ostream>
using namespace std;
class Complex {
double real, image;
public:
Complex(double real=0, double image=0): real(real), image(image) {} //Comstructor
double getReal() { return real; }
double getImage() { return image; }
void setReal(double real) { this->real = real; }
void setImage(double image) { this->image = image; }
friend ostream& operator<<(ostream& os, Complex &cp);
};
ostream& operator<<(ostream& os, Complex &cp) {
os<<"("<<cp.real<<" + "<<cp.image<<"i"<<")";
return os;
}
class Polynomial {
double a, b, c;
public:
Polynomial(int c0=0, int c1=0, int c2=0): a(c0), b(c1), c(c2) {}
Polynomial operator+(const Polynomial& s);
double eval(double x) { return a*x*x + b*x + c; }
void roots();
friend ostream& operator<<(ostream& os, Polynomial& p);
friend istream& operator>>(istream& is, Polynomial& p);
};
Polynomial Polynomial::operator+(const Polynomial& s) {
Polynomial sum;
sum.a += s.a;
sum.b += s.b;
sum.c += s.c;
return sum;
}
void Polynomial::roots() {
double d = b*b - 4.0*a*c;
if(d>=0) {
double root1 = (-b+sqrt(d))/(2.0*a);
double root2 = (-b-sqrt(d))/(2.0*a);
cout<<"Roots are "<<root1<<" and "<<root2<<endl;
}
else {
Complex c1((-b)/(2.0*a), sqrt(abs(d))/(2.0*a));
Complex c2((-b)/(2.0*a), -sqrt(abs(d))/(2.0*a));
cout<<"Roots are "<<c1<<" and "<<c2<<endl;
}
}
ostream& operator<<(ostream& os, Polynomial& p){
os<<"Polynomial is: "<<p.a<<"x^2 +"<<p.b<<"x +"<<p.c<<endl;
return os;
}
istream& operator>>(istream& is, Polynomial& p){
cout<<"Enter coefficients of polynomial (a, b, c in that order)";
is>>p.a>>p.b>>p.c;
return is;
}
int main() {
Polynomial a(2,1,2), b;
cin>>b;
cout<<a;
cout<<b;
a.roots();
b.roots();
}