Program doesn't operate properly

I've got a quite challenging problem here.

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.

//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

        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.

Do you have any ideas?
Thanks for your time :)
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.
By the way, why would pow give 12000.00000001?

Because the power doesn't have to be an integer, for example you could have 21.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.
Last edited on
What Chervil said.

Either that... or... 12000 might not be possible to represent exactly with floating point numbers... so it just gets as close as it can.

This site explains it pretty well:
Last edited on
Thanks a lot guys, this info is really nice.
btw, why don't you use string? you can split them by first knowing their length, right?
Topic archived. No new replies allowed.