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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With