【问题标题】:How can I round Int to nearest 10 in Swift?如何在 Swift 中将 Int 舍入到最接近的 10?
【发布时间】:2019-06-11 07:54:18
【问题描述】:

我有一个小问题,四舍五入到最接近的 10

    var finalResult = Int(textfield.text!)

    let x = Double(finalResult)
    let y = x.rounded() / 5
    print(x) // 18.0
    print(y) // 3.6

我希望结果是这样的

     // if x = 6.0 ... 14.0
     // y = 2 

     // if x = 15.0
     // y = 3 

     // if x = 16.0 ... 24.0 
     // y = 4 

     // if x = 25.0
     // y = 5 

     // if x = 26.0 ... 34.0
     // y = 6

我希望我提出了一个对我和其他人都有益的问题

我希望我已经很好地解释了这个问题

【问题讨论】:

  • 你所有的例子我都不清楚。将 6.0 ... 14.0 舍入到最接近的 10 得到 10 - 为什么您期望结果为 y=2?
  • Round Double to closest 10 的可能重复项。
  • 因为y包含/5
  • 您可以通过不添加 / 5 使该示例更加清晰易懂
  • 谢谢你 Martin R,我尝试了我发送的内容,但我遇到了问题,如果 x = 15 将其舍入为 20,我想保持 15 的原样

标签: swift int double


【解决方案1】:

你需要使用round function和x % 5 == 0检查。

let values = (6...100).map({ Double($0) })

func round(_ value: Double, toNearest: Double) -> Double {
    return round(value / toNearest) * toNearest
}

for x in values {
    if x.truncatingRemainder(dividingBy: 5) == 0 {
        print("x - \(x), y - \(Int(x / 5))")
    } else {
        let rounded = round(x, toNearest: 10.0)
        print("x - \(x), y - \(Int(rounded / 5))")
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2017-07-26
    • 2011-03-21
    • 2014-12-08
    • 2013-08-31
    • 2017-05-03
    • 1970-01-01
    相关资源
    最近更新 更多