如何在scala中得到可被除数整除的最近数

如何在scala中得到可被除数整除的最近数,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 t

如何在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
  }
def findClosestDivisible(被除数:Int,除数:Int):Int=
如果(被除数%除数==0){
//如果股息已经可分割,则返回股息。
股息
}否则{
//求商。
val商=被除数/除数
//第一个可能最接近的数字。
val n1=除数*商
//第二个可能最接近的数字。
val n2=
如果((股息*除数)>0)
除数*(商+1)
其他的
除数*(商-1)
//返回最接近的数字。
导入math.abs
如果(abs(股息-n1)

注意:代码基于上的算法,我只是限制自己在Scala中实现它

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

def makeNum(num:Double,buc:Int):Double={
val符号=如果(num*buc<0)-1其他1
buc*符号*(num/buc*符号).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是你的第一种?你能用什么,你不能用什么这看起来像一个,请阅读提供的链接和基本常见问题解答,如如何提问和mcve。我必须在这里使用scala。我现在正在尝试,但它似乎卡住了。是的,我相信你,但你必须明白这不是免费的编码服务。我们要帮助的不是免费工作。我提出的所有问题都是为了让你向我们表明,你真的试图解决这个问题。首先,请编辑问题证明细节,而不是评论,例如,您是否有解决问题的伪代码?如果是,请加上。您知道如何用任何其他编程语言解决它吗?如果知道,请提供该代码。您是否尝试用Scala解决此问题,但遇到了问题,请提供该代码以及您遇到的确切问题。请编辑问题并使用适当的格式,以便代码可读,而不是注释(然后删除它们)。其次,作为一个建议,创建一个函数,接收输入并返回答案,而不是使用硬编码值。最后,你没有信心到底是什么意思?这个解决方案在数学上正确吗?您是否用许多输入进行过测试?您是否从其他语言知道它,但您不确定代码是否正确?
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