gpt4 book ai didi

负数时 Swift 加倍奇怪

转载 作者:搜寻专家 更新时间:2023-11-01 06:34:35 25 4
gpt4 key购买 nike

Xcode 8.2.1、Swift 3。

import UIKit

extension Double {
/// Linear interpolation.
/// Converts a number in one range to its equivalent in another range.
func interpolate(from: ClosedRange<Int>, to: ClosedRange<Int>) -> Double {
let oldValue = self
let offset = Double(to.lowerBound - from.lowerBound)
let expansion = Double(to.upperBound - to.lowerBound) / Double(from.upperBound - from.lowerBound)

print("\nvalue", oldValue)
print("Sign", self.sign)
print("offset", offset)
print("expansion", expansion)
print("oldLowerbound", Double(from.lowerBound))

let newValue = (oldValue - Double(from.lowerBound)) * expansion + offset
return newValue
}
}
print( 1.0.interpolate(from: 0...10, to: 50...70)) // Prints 52.0. Correct
print(-1.0.interpolate(from: 0...10, to: 50...70)) // Prints -52.0. Expected 48.0.
print((-1.0).interpolate(from: 0...10, to: 50...70)) // Prints 48. Correct.

当单元测试在最(看似)微不足道的代码中揭示意想不到的问题时,它们会为自己付出代价:

(上面的代码将在 iOS playground 中运行。)

有没有一种方法可以扩展Double以使第二个打印语句按预期工作(无需像第三个打印语句那样使用括号)?

最佳答案

Martin R 是正确的,这是评估顺序的问题,遗憾的是(据我所知)中缀运算符(在本例中为 -)不能指定优先级。我想到的唯一方法是自定义插值运算符

infix operator ~|
func ~|(lhs: Double, rhs: (from: ClosedRange<Int>, to: ClosedRange<Int>)) -> Double {
return lhs.interpolate(from: rhs.from, to: rhs.to)
}

所以结果是:

-1.0 ~| (from: 0...10, to: 50...70) // prints 48

并且为了防止 Double 扩展方法 interpolate 被直接调用,它可以被文件私有(private)地封装在同一个文件中。

关于负数时 Swift 加倍奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42970033/

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