I've been working on implementing a string library just for the fun of it, and I've come across the most insane bug... I have it narrowed down to this piece of simple code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int rh = 444;
double numd = 0;
while(rh>0)
{
numd = rh/10.0;
rh = rh/10;
double TheValue = (numd-rh)*10+48;
std::cout << "The value as an int: " << TheValue << std::endl;
char num = TheValue;
std::cout << "The value as a char: " << num << std::endl;
std::cout << "numd: " << numd << " rh: " << rh << std::endl;
}
You can see it clearly prints out that the value of the integer is 52 (which is ASCII character 4) however the char prints out a value of 3, but only on the first loop. The worst part is it will randomly work for some numbers and not others.
If someone could explain this and save me my sanity I would appreciate it.
SOLUTION: apparently subtracting an integer from a double can lead to unexpected results (rounding errors), I'm sure that's what the problem is here
First rule of floating point numbers: do not use them unless really needed.
You do not need any doubles here. As I can see you are just iteration over rh digits and adding 48 to them. All you need is modulo operator and integer division. That is all.