我想生成一个包含所有Integers和.5值以及Int Range的数组.
结果想要:
结果想要:
最小值= 0
最大值= 5
生成的数组= [0,0.5,1,1.5,2,2.5,3,3.5,4,4.5,5]
我知道如何只得到整数值:
阵列(0 … 5)
但不是这个浮动值…
我觉得很清楚,有人有想法吗?
解决方法
使用带有步幅的Array()(from:through:by :):
let arr = Array(stride(from: 0,through: 5,by: 0.5)) print(arr)
06001
如果您的最小值和最大值确实是Int,那么您需要将它们转换为Double:
let min = 0 let max = 5 let step = 0.5 let arr = Array(stride(from: Double(min),through: Double(max),by: step))
警告:
由于nature of floating point math,如果步骤或端点不能精确表示为二进制浮点数,则可能会导致意外结果.
@MartinR举了一个例子:
let arr = Array(stride(from: 0,through: 0.7,by: 0.1)) print(arr)
06004
排除端点0.7,因为该值稍微超出了它.
您可能还想考虑使用map生成数组:
// create array of 0 to 0.7 with step 0.1 let arr2 = (0...7).map { Double($0) / 10 }
这将保证您捕获端点0.7(好吧,它的近似值).
所以,对于你原来的例子:
// create an array from 0 to 5 with step 0.5 let arr = (0...10).map { Double($0) / 2 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。