-2

Whenever I'm trying to divide two integers, I am getting some odd results when the integers are bigger than 21474836 - I thought that it's the case of some data-type limitations, but the integer is obviously much bigger: 2147483647.

As I said, this happens only when two of the integers are bigger than 21474836.

Working (because the integers are lower than 21474836):

(11474836 * 100) / 11474836 // returns 100

Not working:

(211474836 * 100) / 211474836 // returns 0, should 100
(31474830 * 100) / 31474837 // returns -99, should 99~
(40000000 * 100) / 41474837 // returns -7, should 96~

See the live demo here: http://ideone.com/lAeneM

What is the problem?

jub0bs
  • 60,866
  • 25
  • 183
  • 186
Lucas
  • 3,517
  • 13
  • 46
  • 75

3 Answers3

2

When you multiply those values by 100 then the result overflows and set the highest bit, bringing the value into negative territory.

Paolo Brandoli
  • 4,681
  • 26
  • 38
2

Do not forget that 211474836 * 100 is bigger than INT_MAX so you get over the border of an integer. Interpret the values as an int64 and you should get the right results.

Robert
  • 1,235
  • 7
  • 17
2

You've gotten mixed up, 2147483647 is the upper range of a signed long. Integers cap out at 65535 - see this post for details.

Changing the values to unsigned longs gives you the range (0 to 4294967295) needed to solve your issue:

#include <iostream>

using namespace std;

int main()
{
    cout << "Ret1: " << (21474837UL * 100UL) / 21474837UL << endl; // should result 100
    cout << "Ret2: " << (31474830UL * 100UL) / 31474837UL << endl; // should result 99~
    cout << "Ret3: " << (40000000UL * 100UL) / 41474837UL << endl; // should result 96~

    return 0;
}
Community
  • 1
  • 1
  • Thanks... I was simply too tired to notice that. I very appreciate this detailed answer :-) – Lucas Nov 17 '14 at 10:35
  • Consider that if you want to allow signed/negative values (not needed for your calculations in the example though) you can change the `UL` (unsigned long) with `L`(long)! – Robert Nov 18 '14 at 07:06