“pow”的使用含糊不清

2024-05-01

大家好,我尝试过,当有人给出一秒钟时,我会得到十亿秒的实时数据。所以我就写了这样的代码。我必须将第二次乘以 10^9 但出现错误。 “pow”的使用含糊不清。

func gigaSecond( second: Int)-> Int {
    
    var gigasecond : Int
    gigasecond = second * Int(pow(10, 9))
    
   return gigasecond   
}


请注意: The pow()函数返回一个decimal value.

并且,要转换这个decimal值对Int值,人们可以简单地想到以下两个之一:

  1. Int(pow(x, y))... [IE。直接的Decimal to Int转换]
  2. Int(Double(pow(x, y)))... [IE。Decimal to Double to Int一次转换]

然而,这两者都会产生相同的结果Ambiguous use of 'pow'错误(下面的屏幕截图)。

  1. enter image description here
  2. enter image description here

然而有趣的是,如果我们用两行代码打破第二个选项,那就是:
a) Decimal to Double, 进而
b) Double to Int
...它就像一个魅力!

这是您想要的确切功能,无需直接使用Int值(根据需要):

func getGigaSeconds(from seconds: Int) -> Int {

    let gigaPower: Double = pow(10, 9)
    let gigaSeconds = seconds * Int(gigaPower)

    return gigaSeconds
}

EDIT:
The Apple Developer documentation shows that the y parameter of the pow() function is an Int, while both x and the return-type are Decimal. enter image description here


结论:
以下变体有效:

// 1) `y` is a `Double`
let gigaSeconds = Int(pow(10, Double(9)))

// 2) `x` is a `Double`
let gigaSeconds = Int(pow(Double(10), 9))

// 3) Both, `x` and `y` are `Double`
let gigaSeconds = Int(pow(Double(10), Double(9)))

// 4) Both, `x` and `y` are `Int` but the end result is a `Double` (which is then converted to an `Int`
let gigaPower: Double = pow(10, 9)
let gigaSeconds = seconds * Int(gigaPower)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“pow”的使用含糊不清 的相关文章

随机推荐