Arrays Swift中浮点数组中的最大值和最小值
根据,要获得阵列的最大值,我们可以执行以下操作:Arrays Swift中浮点数组中的最大值和最小值,arrays,swift,Arrays,Swift,根据,要获得阵列的最大值,我们可以执行以下操作: let nums = [1, 6, 3, 9, 4, 6]; let numMax = nums.reduce(Int.min, { max($0, $1) }) 既然浮动没有最小值和最大值,我们如何对数组执行相同的操作 let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]; let floats:Array=[2.45,7.21,1.35,10.22,2.45
let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, { max($0, $1) })
既然浮动
没有最小值
和最大值
,我们如何对数组
执行相同的操作
let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3];
let floats:Array=[2.45,7.21,1.35,10.22,2.45,3];
您可以使用-FLT_MAX
,它返回浮点值的最小值
,并用于相同的目的
let numMax = floats.reduce(-FLT_MAX, { max($0, $1) })
对于Double
数组,可以使用-DBL\u MAX
如果您想要浮点的最大值,请使用
FLT\u MAX
FLT\u MIN
是可表示的最小正浮点数。只需使用第一个数组元素作为初始值:
let numMax = floats.reduce(floats[0], { max($0, $1) })
但是,在执行此操作之前,您当然需要检查floats
数组是否为空。这里给出的解决方案适用于
对于可比较元素的所有序列,因此也适用于浮点数数组:
let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
let numMax = maxElement(floats)
Swift 2:
var graphPoints:[Int] = [4, 2, 6, 4, 5, 8, 3]
let maxValue = graphPoints.maxElement()
Swift 4有一个.max()
方法用于数组
例如:
let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
let max = floats.max()
let floats:Array=[2.45,7.21,1.35,10.22,2.45,3]
设max=floats.max()
注意:
max()
返回一个可选值,因此有可能返回为零。谢谢,我不知道FLT\u MIN
。应该是-FLT\u MAX
对于Float
的最小幅值。FLT\u MIN给出了指数的最小值。因此我正在更改我的答案。我在哪里可以找到这些变量的文档?
let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
let max = floats.max()