开发者

Why does the following equation always round up?

size = (size_in_bytes + sizeof(int) - 1) / sizeof(in开发者_如何学Got);

This is more of a math questions than real programming question... Is it because C always round down?


Integer division truncates in C, yes. (i.e. it's round towards zero, not round down.)

By adding "divisor - 1" you make sure that any number which isn't an exact multiple of the divisor gets rounded up. So for example, dividing by 3:

 (0 + 2) / 3 == 0 (0 is an exact multiple)
 (1 + 2) / 3 == 1 (round up)
 (2 + 2) / 3 == 1 (round up)
 (3 + 2) / 3 == 2 (3 is an exact multple)

etc


If size_in_bytes is an integer multiple of sizeof(int), like 2 * sizeof(int), it gives you that multiple, because (sizeof(int)-1)/sizeof(int) is less than one. If size_in_bytes is anything other than an integer multiple of sizeof(int), the remainder when divided by sizeof(int) must be at least one. So (sizeof(int) + that remainder - one) is always >= sizeof(int). So it always rounds up.


When all the arguments are int, the / operator does integer division. This means it will divide the top over the bottom, like one would expect of math, but it will just throw away the remainder. Or, in other words, it will always round towards zero.

With integer division, ( sizeof(int) - 1 ) / sizeof(int) will always be less than one. It is, essentially, the largest not-quite-one value you can have. So adding it to the equation will always add not-quite-one to the final answer, which, when rounded down, will be the same as rounding the original equation up.

Reading this answer back, I realize it makes a lot more sense in my head than it does in words.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜