gpt4 book ai didi

scala - 如何获得可被scala中的除数整除的最接近的数字

转载 作者:行者123 更新时间:2023-12-02 07:58:51 28 4
gpt4 key购买 nike

如何在 scala 中得到能被除数整除的最接近的数。

例如

-if divisor -20 and dividend is 15, the number 15 has to be converted to 20
-if divisor -20 and dividend is 39, the number 39 has to be converted to 40
-if divisor -20 and dividend is 45, the number 45 has to be converted to 60
-if divisor -20 and dividend is 60, the number conversion is not required.

这个我试过了。但它不适用于负数。

def makeNum(num:Double,buc:Int){
if (num % buc == 0) println(num) else
println( buc * (num/buc).ceil )
}
makeNum(39,20) --> 40.0 - working
makeNum(-10,20) --> -0.0 - Not correct

最佳答案

您似乎不需要“最近”的数字,如标题中所述,但实际上需要“下一个”数字,如“远离零”。如果是这样,那么您的原始设计就非常接近了。您只需要考虑符号,如“远离零的方向”。

def makeNum(num :Double, buc :Int) :Double = {
val sign = if (num*buc < 0) -1 else 1
buc*sign * (num/buc*sign).ceil
}

makeNum(39,20) //res0: Double = 40.0
makeNum(-10,20) //res1: Double = -20.0
makeNum(45, -20) //res2: Double = 60.0
makeNum(-7, -3) //res3: Double = -9.0

关于scala - 如何获得可被scala中的除数整除的最接近的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59932651/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com