scala - 如何获得可被scala中的除数整除的最接近的数字
问题描述
如何获得可被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 findClosestDivisible(dividend: Int, divisor: Int): Int =
if (dividend % divisor == 0) {
// Return the dividend if it is already divisible.
dividend
} else {
// Find the quotient.
val quotient = dividend / divisor
// 1st possible closest number.
val n1 = divisor * quotient
// 2nd possible closest number.
val n2 =
if ((dividend * divisor) > 0)
divisor * (quotient + 1)
else
divisor * (quotient - 1)
// Return the closest number.
import math.abs
if (abs(dividend - n1) < abs(dividend - n2)) n1
else n2
}
注意:代码基于此页面上的算法,我只是限制自己在Scala中实现它。
推荐阅读
- java - 为什么这个Java小程序会让MacOS重启?
- dart - 在 Dart 中 - 是否有与 python 的检查模块类似的包?
- mysql - 如何解决共享主机的mysql高使用率问题。由于 MYSQL 高使用率,我的网站托管被暂停
- javascript - 从 WebStorm 运行量角器测试时,在导入语句中获取 Unexpected token {
- java - 应用程序适用于 API 28 但不适用于 26
- c# - 使用 LINQ 进行分组和求和(根据条件)
- java - Restlet解析json请求
- ssas - 使用 MDX 在 SSAS 中创建计算成员
- swift - 检查 SCNNodes 是否在视图中重叠
- laravel - laravel 5.7 中的 Vue