Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing integers

Tags:

c++

integer

I know when dividing integers the default way it works is to discard the fractional part. E.g.,

int i, n, calls = 0;
n = 1;
n /= 3;
printf("N = %i\n", n);
for (i = 1; i > 0; i /= 3) {
    calls++;
}
printf("Calls = %i\n", calls);

The code above prints:

N = 0
Calls = 1

Could you please explain this behavior?

like image 379
Radek Simko Avatar asked Jan 31 '11 22:01

Radek Simko


1 Answers

1 divided by 3 = .3333 (repeating of course), mathematically. You can think of the computer as truncating the .3333 since it is doing integer arithmetic (0 remainder 1).

The for loop executes because i = 1 and 1 > 0. After executing the body of the loop, you divide i by three and i becomes 0, which is not greater than 0.

like image 144
Chad La Guardia Avatar answered Sep 23 '22 17:09

Chad La Guardia