Tom*_*mer 10 math rounding swift
我想绕一个Double到最接近的10.
例如,如果数字是8.0,则舍入到10.如果数字是2.0,则将其舍入为0.
我不知道从哪里开始.你会建议什么?
Mar*_*n R 27
您可以使用该round()函数(将浮点数舍入到最接近的整数值)并应用"比例因子"10:
func roundToTens(x : Double) -> Int {
return 10 * Int(round(x / 10.0))
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
print(roundToTens(4.9)) // 0
print(roundToTens(15.1)) // 20
Run Code Online (Sandbox Code Playgroud)
在第二个例子中,15.1除以十(1.51),舍入(2.0),转换为整数(2)并再次乘以10(20).
斯威夫特3:
func roundToTens(_ x : Double) -> Int {
return 10 * Int((x / 10.0).rounded())
}
Run Code Online (Sandbox Code Playgroud)
或者:
func roundToTens(_ x : Double) -> Int {
return 10 * lrint(x / 10.0)
}
Run Code Online (Sandbox Code Playgroud)
将舍入函数定义为
import Foundation
func round(_ value: Double, toNearest: Double) -> Double {
return round(value / toNearest) * toNearest
}
Run Code Online (Sandbox Code Playgroud)
为您提供更加通用和灵活的方法
let r0 = round(1.27, toNearest: 0.25) // 1.25
let r1 = round(325, toNearest: 10) // 330.0
let r3 = round(.pi, toNearest: 0.0001) // 3.1416
Run Code Online (Sandbox Code Playgroud)
您还可以扩展FloatingPoint协议并添加一个选项来选择舍入规则:
extension FloatingPoint {
func rounded(to value: Self, roundingRule: FloatingPointRoundingRule = .toNearestOrAwayFromZero) -> Self {
(self / value).rounded(roundingRule) * value
}
}
Run Code Online (Sandbox Code Playgroud)
let value = 325.0
value.rounded(to: 10) // 330 (default rounding mode toNearestOrAwayFromZero)
value.rounded(to: 10, roundingRule: .down) // 320
Run Code Online (Sandbox Code Playgroud)