最大和最小的浮在斯威夫特数组 [英] Max and min in an array of Float in Swift

查看:141
本文介绍了最大和最小的浮在斯威夫特数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个答案,以获取最大的数组,我们可以做的:

 让NUMS = [1,6,3,9,4,6]。
让NumMax的值= nums.reduce(Int.min,{最大值($ 0,$ 1)})

我们如何可以做同样的一个阵列<浮动> ,因为没有最大浮动

 让彩车:数组<浮球GT; = [2.45,7.21,1.35,10.22,2.45,3];


解决方案

这里给出的解决方案 http://stackoverflow.com/a /一百十八万七千四百十五分之二千四百一十六万一千〇四工程
为float数组元素可比的所有序列,因此也:

 让彩车:数组<浮球GT; = [2.45,7.21,1.35,10.22,2.45,3]
让NumMax的值= maxElement(花车)


maxElement()在斯威夫特库被定义为

  ///返回`elements`的最大元素。要求:
///`elements`非空。 O(countElements(元素))
FUNC maxElement< R:序列类型,其中R.Generator.Element:可比>(元素:R) - > R.Generator.Element

According to this answer, to obtain the maximum of an array we can do:

let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, { max($0, $1) })

How can we do the same for an Array<Float>, since there's no min and max for Float?

let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3];

解决方案

The solution given here http://stackoverflow.com/a/24161004/1187415 works for for all sequences of comparable elements, therefore also for an array of floats:

let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
let numMax = maxElement(floats)


maxElement() is defined in the Swift library as

/// Returns the maximum element in `elements`.  Requires:
/// `elements` is non-empty. O(countElements(elements))
func maxElement<R : SequenceType where R.Generator.Element : Comparable>(elements: R) -> R.Generator.Element

这篇关于最大和最小的浮在斯威夫特数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆