我正在使用 Swift 进行一些计算。我知道在 Swift 中,0/0 给出 NAN(不是数字)而不是 0。无论如何它会返回 0 吗?
for x in 0..<n {
for y in 0..<n {
if(B[0,y,x]==NAN) {B[0,y,x]=0 } //use of undeclared identifier 'NAN'
println("\((Float)B[0,y,x])")
}
}
最佳答案
NaN 在 FloatingPointType
协议(protocol)中定义。
Which is the Swift equivalent of isnan()?
那么,如果你想要零,使用Overflow Operators怎么样? ?
let x = 1
let y = x &/ 0
// y is equal to 0
[更新]
您可以像这样定义自定义溢出运算符。
func &/(lhs: Float, rhs: Float) -> Float {
if rhs == 0 {
return 0
}
return lhs/rhs
}
var a: Float = 1.0
var b: Float = 0
// this is 0
a &/ b
关于ios - Swift 零除以零得到 NAN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28292000/