-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyFloat.cpp
95 lines (83 loc) · 1.75 KB
/
MyFloat.cpp
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
//
// Created by davilka on 09.11.17.
//
#include <iostream>
#include <typeinfo>
#include "MyFloat.h"
using namespace std;
void MyFloat::print() {
//printf("\nMant+Exp: %1.4f*2**%d Mant: %d Exp: %d Restored: %f",((double) getMant())/10000, getExp(), getMant(), getExp(), this->restore());
//printf("\nMant: %4d, Exp: %d", this->mant, this->exp);
cout << "Mant: " << getMant() << ", Exp: " << getExp() << ", Restored: " << restore() << endl;
}
double MyFloat::restore() {
double fmant;
int mant, exp;
mant = getMant();
exp = getExp();
fmant = (double) mant / 10000;
while (exp > 0) {
fmant *= 2;
exp--;
}
while (exp < 0) {
fmant /= 2;
exp++;
}
return fmant;
}
int MyFloat::getMant() {
return mant;
}
void MyFloat::setMant(int m) {
mant = m;
}
int MyFloat::getExp() {
return expn;
}
void MyFloat::setExp(int e) {
expn = e;
}
MyFloat operator+(MyFloat a, MyFloat b) {
int amant, aexp, bmant, bexp;
amant = a.getMant();
aexp = a.getExp();
bmant = b.getMant();
bexp = b.getExp();
while (aexp > bexp) {
amant *= 2;
aexp--;
}
while (aexp < bexp) {
amant /= 2;
aexp++;
}
return MyFloat(amant + bmant, aexp);
}
MyFloat operator-(MyFloat a, MyFloat b) {
int amant, aexp, bmant, bexp;
amant = a.getMant();
aexp = a.getExp();
bmant = b.getMant();
bexp = b.getExp();
while (aexp > bexp) {
amant *= 2;
aexp--;
}
while (aexp < bexp) {
amant /= 2;
aexp++;
}
return MyFloat(amant - bmant, aexp);
}
MyFloat operator*(MyFloat a, MyFloat b) {
return MyFloat((a.getMant() * b.getMant()) / 10000, a.getExp() + b.getExp());
}
MyFloat operator/(MyFloat a, MyFloat b) {
if (b.getMant() != 0) {
return MyFloat((a.getMant() / b.getMant()) * 10000, a.getExp() - b.getExp());
} else {
cout << "Error: Divide by Zero" << endl;
exit(-1);
}
}