I've made a function with the purpose of splitting number's digits by half, something like this:
123456 --> 123 and 456
12345 --> 12 and 345 (when the number of digits is odd, first half is always one digit smaller than the other one.)
Apparently works fine, but I'm having a problem with some numbers with odd amounts of digits. The problem is, the function returns the second half minus one. For example:
12345 --> 12 and 344
This is the code, and I suspect the problem may be in the bold line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//Number is the number that has to be split, Length is the amount of digits the number has.
void Number_splitter(int Number, int Length, int &First_half, int &Second_half){
//If number is even
if(Length%2==0){
First_half= Number/pow(10,(Length/2));
Second_half= Number - (First_half*pow(10,(Length/2)));
}
//If number is odd
else {
First_half = Number/pow(10, ((Length)/2)+1);
Second_half = Number - (First_half*pow(10, ((Length)/2)+1));
}
}
I've checked the program's process for 12345 several times with the debugger, and the operation it does is 12345 - 12*1000, so I just don't know what to do right now.
pow() is a floating point math function, which means it does floating point math and therefore has rounding errors.
(First_half*pow(10, ((Length)/2)+1)) is probably giving you something like 12000.00000001.
So then 12345 - 12000.000001 = 344.9999999, which gets truncated to 344 when you cast back to an integer.
My first advise would be to avoid using pow entirely as there's no reason for it here. You should be able to achieve this with use of *, /, and % operators.
When dealing with integers, its best to stay with integers. Converting floating point to integer (especially if you need precision) is typically something you want to avoid unless its necessary.
Mmmm... Really interesting. I will try to do it without pow, thanks a lot for your help!
By the way, why would pow give 12000.00000001? I can't think of any reason for that.
Because the power doesn't have to be an integer, for example you could have 2^{1.5} or pow(2, 1.5) the internal operation probably does something like taking the log of the number, multiplying by the power and then getting the antilog of that. Since log() and exp() will use floating point calculations on non-integer values, some approximation is inevitable, though the details of the implementation may vary.