-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRational.cpp
More file actions
53 lines (44 loc) · 1.46 KB
/
Rational.cpp
File metadata and controls
53 lines (44 loc) · 1.46 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
//Rational.cpp
#include <iostream>
#include <string>
#include "Rational.h"
using namespace std;
int Rational::gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
Rational::Rational(int num, int denom) {
int common = gcd(num, denom);
numerator = num / common;
denominator = denom / common;
}
Rational Rational::add(const Rational& other) const {
int num = numerator * other.denominator + other.numerator * denominator;
int denom = denominator * other.denominator;
return Rational(num, denom);
}
Rational Rational::subtract(const Rational& other) const {
int num = numerator * other.denominator - other.numerator * denominator;
int denom = denominator * other.denominator;
return Rational(num, denom);
}
Rational Rational::multiply(const Rational& other) const {
int num = numerator * other.numerator;
int denom = denominator * other.denominator;
return Rational(num, denom);
}
Rational Rational::divide(const Rational& other) const {
int num = numerator * other.denominator;
int denom = denominator * other.numerator;
return Rational(num, denom);
}
std::string Rational::toRationalString() const {
return std::to_string(numerator) + "/" + std::to_string(denominator);
}
void Rational::display() const {
std::cout << toRationalString();
}
double Rational::toDouble() const {
return static_cast<double>(numerator) / denominator;
}