Skip to content

Instantly share code, notes, and snippets.

@AmosAidoo
Last active April 29, 2020 19:48
Show Gist options
  • Save AmosAidoo/77c68d8c51bd61da3944efd39361fea4 to your computer and use it in GitHub Desktop.
Save AmosAidoo/77c68d8c51bd61da3944efd39361fea4 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cmath>
using namespace std;
class Polynomial {
double a,b,c;
public:
Polynomial() {} //Default constructor
Polynomial(const Polynomial& poly_old); //Copy constructor
Polynomial(double a, double b, double c) {
this->a = a;
this->b = b;
this->c = c;
}
Polynomial operator+(const Polynomial& poly);
Polynomial operator-(const Polynomial& poly);
void operator++(int);
void operator--(int);
bool operator==(const Polynomial& poly);
void showpoly();
void roots();
//Getters
double getA() const {return a;}
double getB() const {return b;}
double getC() const {return c;}
//Setters
void setA(double val) {a = val;}
void setB(double val) {b = val;}
void setC(double val) {c = val;}
~Polynomial() {} //Default destructor
};
Polynomial::Polynomial(const Polynomial& poly_old) {
a = poly_old.getA();
b = poly_old.getB();
c = poly_old.getC();
}
Polynomial Polynomial::operator+(const Polynomial& poly) {
Polynomial tmp;
tmp.setA(a + poly.getA());
tmp.setB(b + poly.getB());
tmp.setC(c + poly.getC());
return tmp;
}
Polynomial Polynomial::operator-(const Polynomial& poly) {
Polynomial tmp;
tmp.setA(a - poly.getA());
tmp.setB(b - poly.getB());
tmp.setC(c - poly.getC());
return tmp;
}
void Polynomial::operator++(int) {
a++; b++; c++;
}
void Polynomial::operator--(int) {
a--; b--; c--;
}
bool Polynomial::operator==(const Polynomial& poly) {
return (poly.getA() == a) && (poly.getB() == b) && (poly.getC() == c);
}
void Polynomial::showpoly() {
char bb, bc;
//Set the operators
bb = (b < 0) ? '-' : '+';
bc = (c < 0) ? '-' : '+';
//Print out the polynomials
if (a == 0) {
cout << b << "x " << bc << " " << abs(c) << "\n";
if (b == 0) cout << c << "\n";
} else if (b == 0) {
cout << a << "x^2 " << bc << " " << abs(c) << "\n";
}
else cout << a << "x^2 " << bb << " " << abs(b) << "x " << bc << " " << abs(c) << "\n";
}
void Polynomial::roots() {
double x1, x2;
x1 = (-b + sqrt(b*b - 4*a*c)) / 2*a;
x2 = (-b - sqrt(b*b - 4*a*c)) / 2*a;
//Prints out -nan for complex roots
if (x1 == x2) {
cout << x1 << "\n";
} else {
cout << x1 << " " << x2 << "\n";
}
}
int main() {
//Testing the class
Polynomial f(1, -2, -3);
Polynomial g(1, 5, 7);
f.showpoly();
f.roots();
Polynomial f_copy = f;
Polynomial y(1, 1, 1);
Polynomial z = f + y;
f_copy.showpoly();
z.showpoly();
cout << (f_copy == f) << "\n";
cout << (f == z) << "\n";
g++;
g.showpoly();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment