forked from pkivolowitz/asm_book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrounding.cpp
35 lines (30 loc) · 833 Bytes
/
rounding.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
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
template <typename T>
int RoundAwayFromZero(T x) {
return int((x < 0) ? floor(x) : ceil(x));
}
int main() {
int32_t iv;
float fv = 5.1;
iv = (int(fv) == fv) ? int(fv) : int(fv) + ((fv < 0) ? -1 : 1);
cout << setw(4) << fv << " away from zero (should be 6): ";
cout << iv << endl;
fv = -fv;
iv = (int(fv) == fv) ? int(fv) : int(fv) + ((fv < 0) ? -1 : 1);
cout << setw(4) << fv << " away from zero (should be -6): ";
cout << iv << endl;
cout << endl;
cout << "Using MyRound()\n";
fv = -fv;
iv = RoundAwayFromZero(fv);
cout << setw(4) << fv << " away from zero (should be 6): ";
cout << iv << endl;
fv = -fv;
iv = RoundAwayFromZero(fv);
cout << setw(4) << fv << " away from zero (should be -6): ";
cout << iv << endl;
return 0;
}