I know that when dividing integers by default, it works to discard the fractional part. For instance,
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);
Above code:
N = 0 Calls = 1
Could you explain this behavior?
1 is divided by 3 = .3333 (repeated, of course), mathematically. You may think that the computer truncates .3333 as it performs integer arithmetic ( 0remainder 1).
0
1
The cycle foris executed because i = 1and 1 > 0. After completing the body of the loop, you divide iby three and ibecome 0, which is not more than 0.
for
i = 1
1 > 0
i
while, .
while
i = 1; while ( i > 0 ) { calls++; i /= 3; //This becomes .3333, which truncates to zero }
.
for , i > 0 1 > 0, , .
i > 0
? : 1/3 = 0.33333..., , 0.
, for - :
i=1; while(i>0) { calls++; i/=3; }
, i 1; while , i, 1, 0. calls 0 1, 1. i 3, 0 ( ). while , i 0, . calls 1, .
calls
n - int, , double float
Since in integer arithmetic the answer to 1 divided by 3 is 0 with the remainder 1. If you separate two integers, you get integer arithmetic. If you need floating point arithmetic, you need at least one of the operands to be a floating point value.
Everything is very simple.
int i, n, calls = 0; // Set calls to 0 n = 1; // n is now 1 n /= 3; // n /= 3 = 1/3 = 0 printf("N = %i\n", n); for (i = 1; i > 0; i /= 3) { // 1/3 = 0 calls++; // runs once } printf("Calls = %i\n", calls);
Hope this helps.