3

I just wanted to know that is there a way of implementing ceil function without using if-else? With if-else (for a/b) it can be implemented as:

if a%b == 0:
    return(a/b)
else:
    return(a//b + 1)
4

3 回答 3

9

最简单的是。

a//b + bool(a%b)

而只是为了安全,

b and (a//b + bool(a%b))

干杯。

于 2013-06-17T04:26:50.697 回答
6

如果它们是整数,这样应该可以工作(我猜你有一个有理数表示):

a/b + (a%b!=0)

否则,请替换a/bint(a/b),或者更好,如下所示a//b

于 2013-06-17T04:18:21.267 回答
3
-(-a//b)

Perhaps the simplest?

========================

*Edited per @Gilles's comment:

for an integer n,

floor(x)=n for x in [n, n+1)
ceil(y)=n+1 for y in (n, n+1]

So, floor(-y)=-n-1 for -y in [-n-1, -n),

and ceil(y)=-floor(-y)=n+1 for y in (n, n+1]

In Python, floor(a/b) = a//b. Thus ceil(a/b) = -(-a//b)

于 2019-10-06T00:29:12.327 回答