【问题标题】:Check if an integer is divisible by another integer (Swift)检查一个整数是否可以被另一个整数整除(Swift)
【发布时间】:2015-01-26 08:52:09
【问题描述】:

我需要检查一个整数是否能被另一个整数整除。

如果不是,我想将其四舍五入到最接近的倍数。

例子:

var numberOne = 3
var numberTwo = 5

numberTwo 不是 numberOne 的倍数,因此我希望将 numberTwo 舍入到 6。

我该怎么做? 谢谢

【问题讨论】:

    标签: ios swift integer division


    【解决方案1】:

    您可以使用模运算符%

    numberTwo % numberOne == 0
    

    模求2个数之间整数除法的余数,例如:

    20 / 3 = 6
    20 % 3 = 20 - 6 * 3 = 2
    

    20/3 的结果是 6.666667 - 被除数 (20) 减去除数乘以除数 (3 * 6) 的整数部分是模 (20 - 6 * 3) ,在这种情况下等于 2 .

    如果模数为零,则被除数是除数的倍数

    this wikipedia 页面了解有关模数的更多信息。

    【讨论】:

    • 第一部分对我有用,但我不确定底线是什么意思。如何计算出我应该添加到 20 以使其可被 3 整除?我想把它四舍五入。谢谢
    • 更新了答案 - 希望能解释一下。
    【解决方案2】:

    1)如果要检查或一个整数除以另一个整数:

    斯威夫特 5

    if numberOne.isMultiple(of: numberTwo) { ... }
    

    Swift 4 或更低

    if numberOne % numberTwo == 0 { ... }
    

    2) 舍入到最接近的倍数的函数:

    func roundToClosestMultipleNumber(_ numberOne: Int, _ numberTwo: Int) -> Int {
        
        var result: Int = numberOne
        
        if numberOne % numberTwo != 0 {
    
            if numberOne < numberTwo {
                result = numberTwo
            } else {
                result = (numberOne / numberTwo + 1) * numberTwo
            }
        }
        
        return result
    }
    

    【讨论】:

      【解决方案3】:

      斯威夫特 5

      isMultiple(of:)

      如果此值是给定值的倍数,则返回 true 值,否则为假。

      func isMultiple(of other: Int) -&gt; Bool

      let rowNumber = 4
      
      if rowNumber.isMultiple(of: 2) {
          print("Even")
      } else {
          print("Odd")
      }
      

      【讨论】:

        【解决方案4】:

        您可以使用truncatingRemainder。例如,

        if number.truncatingRemainder(dividingBy: 10) == 0 {                
            print("number is divisible by 10")   
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-26
          • 1970-01-01
          • 1970-01-01
          • 2011-01-06
          • 1970-01-01
          相关资源
          最近更新 更多