【问题标题】:Swift get Fraction of FloatSwift 得到浮点数的分数
【发布时间】:2014-07-28 14:01:52
【问题描述】:

我最近一直在尝试 swift,但遇到了一个相当简单的问题。

在 Obj-C 中,当我想获取浮点数的小数位数时,我会执行以下操作:

float x = 3.141516
int integer_x = (int)x;
float fractional_x = x-integer_x;
//Result: fractional_x = 0.141516

在斯威夫特中:

let x:Float = 3.141516
let integerX:Int = Int(x)
let fractionalX:Float =  x - integerX 

-> 由于类型错误,这会导致错误

任何想法如何正确地做到这一点?

提前致谢

马耳他

【问题讨论】:

  • 除了文字之外,Swift 中没有自动转换。所以 Swift 不允许你用 x,一个 Float 和 integerX,一个 Int 来做数学运算。您需要将其转换回浮点数:x - Float(integerX)。但是看看下面我的回答,我觉得它应该更适合你。

标签: objective-c math swift type-conversion


【解决方案1】:

使用modf函数:

let v = 3.141516
var integer = 0.0
let fraction = modf(v, &integer)
println("fraction: \(fraction)");

输出:

分数:0.141516

对于 float 而不是 double 只需使用:modff

【讨论】:

  • modf 实际上返回一个元组。
  • 不,它返回双精度:double modf(double value, double *iptr);,参见:developer.apple.com/library/mac/documentation/Darwin/Reference/…
  • 是的,它确实返回了一个元组。点击 Darwin 并查看函数: func modf(value: Double) -> (Double, Double) 。 (我猜文档不是最新的。无论如何谁会阅读文档。)
  • 你说的都是对的。有func modf(_: Double, _: UnsafePointer<Double>) -> Double func modf(value: Double) -> (Double, Double) 以及浮点变体。前者是从<math.h>导入的,后者似乎只有Swift。
  • 我可以确认 let (a, b) = modf(x)let d = modf(x, &c) 在编译的应用程序和我的 Playground 文件中都有效。 - 实际上我觉得let (a, b) = modf(x) 更优雅,但是你的代码编译和工作对我来说没有问题。
【解决方案2】:

使用 .truncatingRemainder(dividingBy:) 替换模运算符 (x % 1),它(用于模)

  • 立即(只有一个字符),并且
  • 只有很少的 cpu 周期(大概只有一个周期,因为模是常见的 cpu 指令)

给出小数部分。

let x:Float = 3.141516
let fracPart =  x.truncatingRemainder(dividingBy: 1) // fracPart is now 0.141516

fracPart 将假定值:0.141516。这适用于doublefloat

【讨论】:

    【解决方案3】:

    问题是你不能减去 Float 和 Int,你应该将其中一个值转换为与另一个相同,尝试一下:

    let fractionalX:Float = x - Float(integerX)
    

    【讨论】:

      【解决方案4】:

      Swift 3 不喜欢模数运算符%。它要我使用Double 类型的truncatingRemainder

      let x1:Double = 123.00
      let t1 = x1.truncatingRemainder(dividingBy: 1)
      print("t1 = \(t1)")
      let x2:Double = 123.45
      let t2 = x2.truncatingRemainder(dividingBy: 1)
      print("t2 = \(t2)")
      

      产生输出:

      t1 = 0.0
      t2 = 0.450000000000003
      

      要删除第 3 万亿次伪影,您可能应该对结果进行四舍五入。

      【讨论】:

        【解决方案5】:

        为什么要使用 int?

        这个怎么样:

        import Darwin
        
        let x = 3.1415926
        let xf = x - (x > 0 ? floor(x) : ceil(x))
        

        这里默认使用双打。如果您需要,请随意使用浮点数:

        let x: Float = 3.1415926
        

        这就是你要找的吗?

        【讨论】:

        • 因为问题只是关于浮点数的分数。
        • let ( _ , fraction ) = modf(x) 也可以,不管你的船是什么。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-05
        • 1970-01-01
        • 2019-10-16
        • 1970-01-01
        • 2018-05-18
        相关资源
        最近更新 更多