结构中的 Swift 浮动问题 [英] Issue with Swift Floats inside Structs

查看:35
本文介绍了结构中的 Swift 浮动问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,当它在结构中时,swift 正在改变我的浮点值.我认为这不会发生在旧版本的 swift 上,但它现在发生在 4.1 上.下面的代码示例...想法?

var f = Float(4.111)print(f)//打印 4.111结构浮动容器{var f:浮动}让容器 = FloatContainer(f: f)print(container)//打印 FloatContainer(f: 4.11100006)

解决方案

这是一个常见的舍入错误,因为二进制不能表示一些十进制数.请查看

至于直接打印浮点数和打印具有浮点数属性的对象之间的区别,归结为实现 description 的对象的description 属性code>CustomStringConvertible 协议.当 print 函数想要打印到控制台时,它会调用 _print_unlocked,这是一个内部函数,有这个块:

if case let printableObject as CustomStringConvertible = value {printableObject.description.write(to: &target)返回}

因此您可以将代码更改为此以获得预期的输出:

struct FloatContainer : CustomStringConvertible {变量描述:字符串{得到 {返回 f. 说明}}var f:浮动}

I'm having an issue where swift is changing my float value when it's inside a struct.. I dont think this happened on older versions of swift, but it is happening now on 4.1. Code example below... thoughts?

var f = Float(4.111)

print(f) // prints 4.111

struct FloatContainer {
    var f: Float
}

let container = FloatContainer(f: f)

print(container) // prints FloatContainer(f: 4.11100006)

解决方案

That's a common rounding error, since binary can't represent some decimal numbers. Have a look here.

Here is an online converter from a decimal to a floating-point representation. As you can see there is an error (6.103515625E-8) due to the conversion:

As to the difference between when you print a float directly, or when you print an object that has a property that is a float, it comes down to the description property of objects that implement the CustomStringConvertible protocol. When the print function wants to print to the console, it invokes _print_unlocked, which is an internal function that has this block:

if case let printableObject as CustomStringConvertible = value {
    printableObject.description.write(to: &target)
    return
}

So you could change your code to this in order to have the expected output:

struct FloatContainer : CustomStringConvertible {
    var description: String {
        get {
            return f.description
        }
    }
    var f: Float
}

这篇关于结构中的 Swift 浮动问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆