Dividing integers

北城余情 提交于 2019-12-19 19:55:19

问题


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:


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.




回答2:


rewrite as while and it becomes apparent.

i = 1;
while ( i > 0 )
{
    calls++;        
    i /= 3; //This becomes .3333, which truncates to zero
}



回答3:


Because it executes the loop once.

The loop increment in for is executed after the loop body, and at loop entry i > 0 is true as 1 > 0, on the next loop division occurs and then the test become false and loop exit.




回答4:


Where's the problem? The first line of output is immediate: 1/3=0.33333..., removing the fractional part it's 0.

For the second line keep in mind that the for cycle is translated to something like this:

i=1;
while(i>0)
{
    calls++;
    i/=3;
}

So, at start i is 1; the first iteration of the while is executed because i, being 1, is greater than 0. calls is 0 and is incremented by 1, thus gets to 1. i is divided by 3, so it gets to 0 (because the fractional part is not computed in integer division). The while condition check is performed again, but now i is 0, thus the cycle is not repeated. calls remains to 1 and this value is printed on the screen.




回答5:


n is an int, a division will return an integer and no double or float




回答6:


Because in integer arithmetic, the answer to 1 divided by 3 is 0 with a remainder of 1. If you divide two integers, you get integer arithmetic. If you want floating point arithmetic, you need at least one of the operands to be a floating point value.




回答7:


It's all 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.



来源:https://stackoverflow.com/questions/4857091/dividing-integers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!