gpt4 book ai didi

Swift - `范围最小 - 最大范围内的数字

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:50 24 4
gpt4 key购买 nike

如何缩放数字以适应指定范围?例如,如果我有:

Input_min = 10.1;
Input_max = 750.0;

Range_min = 0.0;
Range_max = 350.0;

example Input_n = 503.9;

如何使用 swift 使任何数字在最小值和最大值范围内缩放?

最佳答案

编辑/更新:Xcode 11.5 • Swift 5.2

extension FloatingPoint {
func converting(from input: ClosedRange<Self>, to output: ClosedRange<Self>) -> Self {
let x = (output.upperBound - output.lowerBound) * (self - input.lowerBound)
let y = (input.upperBound - input.lowerBound)
return x / y + output.lowerBound
}
}

extension BinaryInteger {
func converting(from input: ClosedRange<Self>, to output: ClosedRange<Self>) -> Self {
let x = (output.upperBound - output.lowerBound) * (self - input.lowerBound)
let y = (input.upperBound - input.lowerBound)
return x / y + output.lowerBound
}
}

let integer = 380
let result = integer.converting(from: 10...750, to: 100...350) // 225

let double = 750.0
let result = double.converting(from: 10.1...750.0, to: 0...350) // 350

关于Swift - `范围最小 - 最大范围内的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31274411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com