I am using the following arithmetic to convert a fraction to its hex equivalent:
.142857 * 16 = 2.285712
.285712 * 16 = 4.571429
Where I keep multiplying the remainder until it is either equal to the original remainder or zero.
So I wrote this function to try to perform this arithmetic recursively:
int * getHex(int * arr, double original, double result, int index) {
double newResult, fraction, integer;
newResult = result;
fraction = modf(newResult, &integer);
cout << "fraction " << fraction << " the result " << rem << endl;
arr[index] = (int)integer;
if(fraction == original) cout << "test" << endl;
if (fraction == 0 || fraction == original) {
return arr;
}
index += 1;
return resultToHex(hexArr, result, fraction * 16, index);
}
I am calling this method like so:
int * arr = new int[100];
int num = stoi(numerator, nullptr, 16);
int den = stoi(denominator, nullptr, 16);
double rem = 1 + ( (double)(num - den) / den);
double result = rem * 16;
arr = getHex(arr, rem, result, 0);
The problem is that fraction
never equals rem
being passed in, even though when I cout
I see that at some point fraction
definitely equals rem
. An example of what I am talking about:
Where numerator is 1 and denominator is 7:
rem = .142857
result = 2.28571
Then I call the function, passing in the above as arguments:
getHex(arr, rem, result, 0);
and this is the result of the cout
inside getHex
:
the fraction 0.285714 result 0.142857
the fraction 0.571429 result 0.142857
the fraction 0.142857 result 0.142857 // the fraction equals the original remainder
the fraction 0.285714 result 0.142857
the fraction 0.571429 result 0.142857
the fraction 0.142857 result 0.142857
the fraction 0.285714 result 0.142857
the fraction 0.571429 result 0.142857
the fraction 0.14286 result 0.142857
the fraction 0.285767 result 0.142857
the fraction 0.572266 result 0.142857
the fraction 0.15625 result 0.142857
the fraction 0.5 result 0.142857
the fraction 0 result 0.142857
I cannot figure out why my function continues to execute even though after the third iteration the fraction equals the remainder. I cannot find the bug. What am I missing here?