cmpsc330hw3/exact_number.cxx

126 lines
2.8 KiB
C++
Raw Permalink Normal View History

2024-11-04 21:33:28 +00:00
// Name: Sandipsinh Rathod
// Email: sdr5549@psu.edu
// Class: CMPSC 330
// Program Exact Number
// Current Date: 4/11/24 4:25 PM
// Due Date: 5/11/24
//
// Description:
// Implementation for +, -, *, /, =, +=, -=, *=, /=, ==, !=, <, >, <=, >= etc.
2024-11-04 21:23:07 +00:00
#include "exact_number.h"
using namespace std;
ExactNumber::ExactNumber(){
numer = 0;
denom = 1;
}
ExactNumber::ExactNumber(int n, int d){
if (!d) {
throw logic_error("Denominator can not be zero.");
}
2024-11-04 21:23:07 +00:00
numer = n;
denom = d;
simplify();
}
ExactNumber::ExactNumber(const ExactNumber& n) {
numer = n.numer;
denom = n.denom;
}
ExactNumber::~ExactNumber() {
}
ExactNumber& ExactNumber::operator=(const ExactNumber& rhs) {
numer = rhs.numer;
denom = rhs.denom;
return *this;
}
ExactNumber& ExactNumber::operator+=(const ExactNumber& rhs) {
numer = numer * rhs.denom + denom * rhs.numer;
denom *= rhs.denom;
simplify();
return *this;
}
ExactNumber& ExactNumber::operator-=(const ExactNumber& rhs) {
numer = numer * rhs.denom - denom * rhs.numer;
denom *= rhs.denom;
simplify();
return *this;
}
ExactNumber& ExactNumber::operator*=(const ExactNumber& rhs) {
numer *= rhs.numer;
denom *= rhs.denom;
simplify();
return *this;
}
ExactNumber& ExactNumber::operator/=(const ExactNumber& rhs) {
numer *= rhs.denom;
denom *= rhs.numer;
simplify();
if (!denom) {
throw logic_error("Division by 0");
}
2024-11-04 21:23:07 +00:00
return *this;
}
ExactNumber operator+(const ExactNumber& lhs, const ExactNumber& rhs) {
ExactNumber result(lhs);
result += rhs;
return result;
}
ExactNumber operator-(const ExactNumber& lhs, const ExactNumber& rhs) {
ExactNumber result(lhs);
result -= rhs;
return result;
}
ExactNumber operator*(const ExactNumber& lhs, const ExactNumber& rhs) {
ExactNumber result(lhs);
result *= rhs;
return result;
}
ExactNumber operator/(const ExactNumber& lhs, const ExactNumber& rhs) {
ExactNumber result(lhs);
result /= rhs;
return result;
}
bool ExactNumber::operator==(const ExactNumber& rhs) const {
return numer == rhs.numer && denom == rhs.denom;
}
bool ExactNumber::operator!=(const ExactNumber& rhs) const {
return numer != rhs.numer || denom != rhs.denom;
}
bool ExactNumber::operator<(const ExactNumber& rhs) const {
return numer * rhs.denom < denom * rhs.numer;
}
bool ExactNumber::operator>(const ExactNumber& rhs) const {
return numer * rhs.denom > denom * rhs.numer;
}
bool ExactNumber::operator<=(const ExactNumber& rhs) const {
return numer * rhs.denom <= denom * rhs.numer;
}
bool ExactNumber::operator>=(const ExactNumber& rhs) const {
return numer * rhs.denom >= denom * rhs.numer;
}
ostream& operator<<(ostream& os, const ExactNumber& n) {
os << n.numer << "/" << n.denom;
return os;
2024-11-04 21:23:18 +00:00
}