如果整数除法的余数不为零,我想继续将结果向上舍入。
例子:
5 / 2产量2. 但我想继续3(整数)。4 / 2产量2,这对于我的用例来说很好。我目前采用这种笨重的结构:
ceil(5 / 2.toDouble()).toInt()
Run Code Online (Sandbox Code Playgroud)
Kotlin 游乐场上的示例:https ://pl.kotl.in/eX0rYXnsH
有没有更惯用的方法来实现这一目标?
缺少的是ceilDiv。尽管 std lib 是否应该实现这一点仍然是(正在讨论中),但我们可以借助以下方法来实现floorDiv:
/** Divides this value by the other value, ceiling the result to an integer that is closer to positive infinity. */
fun Int.ceilDiv(other: Int): Int {
return this.floorDiv(other) + this.rem(other).sign.absoluteValue
}
Run Code Online (Sandbox Code Playgroud)
fun main() {
println((-2).ceilDiv(2)) // -1
println((-1).ceilDiv(2)) // 0
println(0.ceilDiv(2)) // 0
println(1.ceilDiv(2)) // 1
println(2.ceilDiv(2)) // 1
println(3.ceilDiv(2)) // 2
println(4.ceilDiv(2)) // 2
println("-----")
println((-2).ceilDiv(-2)) // 1
println((-1).ceilDiv(-2)) // 1
println(0.ceilDiv(-2)) // 0
println(1.ceilDiv(-2)) // 0
println(2.ceilDiv(-2)) // -1
println(3.ceilDiv(-2)) // -1
println(4.ceilDiv(-2)) // -2
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
149 次 |
| 最近记录: |