如果我将 3 除以 2,我希望答案为 2(即 1.5 四舍五入为 2)
C语言中如何求一个数的上限?
如果我将 3 除以 2,我希望答案为 2(即 1.5 四舍五入为 2)。
How to get he upper limit of a number in C?
If I divide 3 by 2 I want the answer to be 2 (ie 1.5 rounded to 2).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果您只对除以 2 感兴趣,那么只需取 (n + 1) / 2 即可将其保留为整数数学。例如 (3 + 1) / 2 给出 2。对于更大的数字 x,请使用 x - 1。例如,(3 + 7) / 8 = 1,对于 3 除以 8。
对于一般情况,您正在寻找天花板函数——ceil。在 Google 上快速搜索“math ceil C”,此页面位于结果顶部: http://www.elook.org/programming/c/ceil.html
If you are just interested in dividing by 2, then just take (n + 1) / 2 to keep it in integer math. For example (3 + 1) / 2 gives 2. For a larger number x, use x - 1. For example, (3 + 7) / 8 = 1, for 3 divided by 8.
For the general case, you are looking for the ceiling function -- ceil. A quick Google search for "math ceil C" gave this page at the top of the results: http://www.elook.org/programming/c/ceil.html
ceil(number)
ceil(number)
请注意,操作数之一应该是 double(或 float),因为 3/2 给你 1
Note that one the operands should be double(or float) because 3/2 gives you 1
要不使用函数进行舍入,只需在除法之前添加除数的一半即可。
如果除数是常量,编译器可以很好地优化代码。
To round without using functions, just add half of the divisor before you divide.
if the divisor is a constant, the compiler with optimize the code nicely.
(如果这符合线程死灵术,请通知我,我将删除它)
返回向上舍入商的快速方法是将除数减一添加到被除数中,然后除以。
或者,相应地
,您将通过从 3 中减去 1,除以 2,然后加 1 来进行工作。
我将尝试并解释为什么这是有效的。如果被除数和除数都是浮点数,则等价于(被除数/除数)的截断整数将相等如果除数能完全除除被除数,则等于商的上限;如果不能完全除除被除数,则减一。通过减去 1,我们保证新的被除数 dividend - 1 在除以 divisor 时,将始终返回小于浮点商上限的值。
现在剩下的就是在这个商上加 1,顺便说一句,它是下限((float) 被除数 / (float) 除数)。
(If this qualifies as thread necromancy, kindly notify and I'll delete this)
A quick way to return an upward-rounded quotient is to add the divisor, minus one, to the dividend, and divide.
or alternatively,
Consequentially, you'll work by subtracting 1 from 3, dividing by 2, and adding 1.
I'll try and explain why this works. If dividend and divisor were both floats, then the truncated integer equivalent of (dividend/divisor) would be equal to the ceiling of the quotient if divisor perfectly divides dividend, or one less if it does not perfectly divide dividend. By subtracting 1, we guarantee that the new dividend, dividend - 1, when divided by divisor, will always return a value lesser than the ceiling of the floating point quotient.
All that remains now is adding 1 to this quotient, which, incidentally, is floor((float) dividend / (float) divisor).