-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fraction.h
109 lines (85 loc) · 2.2 KB
/
Fraction.h
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#ifndef FRACTION_H_INCLUDED
#define FRACTION_H_INCLUDED
#include <iostream>
#include <ostream>
#include <cstring>
#include <assert.h>
#include <stdint.h>
class Fraction
{
using Integer = std::int64_t;
public:
Integer num;
Integer den;
Fraction(Integer numm = 0, Integer denm = 1) : num(numm), den(denm)
{
if(den == 0)
throw std::domain_error("denominator 0(zero) exception");
}
Fraction (Fraction n, Fraction d) : num(n.num * d.den), den(n.den * d.num)
{
if(den == 0)
throw std::domain_error("denominator 0(zero) exception");
}
friend std::ostream& operator<< (std::ostream& os, const Fraction& fr);
std::string to_string() const;
bool is_integer()
{
return den == 1;
}
explicit operator bool() const
{
return num != 0;
}
bool operator== (const Fraction& fr) const
{
return num == fr.num && den == fr.den;
}
bool operator!= (const Fraction& fr) const
{
return !(*this == fr);
}
bool operator<(const Fraction& fr)
{
return num * fr.den < den * fr.num;
}
bool operator>(const Fraction& fr)
{
return !(*this <= fr);
}
bool operator<=(const Fraction& fr)
{
return *this == fr || *this < fr;
}
bool operator>=(const Fraction& fr)
{
return !(*this < fr);
}
Fraction operator-() const
{
return { -num, den };
}
Fraction operator+() const
{
return *this;
}
double to_double()
{
return double(num) / den;
}
float to_float()
{
return float(num) / den;
}
void simplify();
friend Fraction operator+(const Fraction& lhs, const Fraction& rhs);
friend Fraction operator-(const Fraction& lhs, const Fraction& rhs);
friend Fraction operator*(const Fraction& lhs, const Fraction& rhs);
friend Fraction operator/(const Fraction& lhs, const Fraction& rhs);
void operator+= (const Fraction& fr);
void operator-= (const Fraction& fr);
void operator*= ( const Fraction& fr);
void operator/= (const Fraction& fr);
};
Fraction pow_fract(const Fraction& fr, int x);
#endif // FRACTION_H_INCLUDED