制作阵列斯威夫特我的函数计算平均 [英] Making my function calculate average of array Swift
本文介绍了制作阵列斯威夫特我的函数计算平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的函数来计算我的双类型的数组的平均值。该阵列被称为内容。现在,我有10个号码。
I want my function to calculate the average of my Double type array. The array is called "votes". For now, I have 10 numbers.
当我称之为平均函数
来得到数组票平均水平,这是行不通的。
When I call the average function
to get the average of the array votes, it doesn't work.
下面是我的code:
var votes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
func average(nums: Double...) -> Double {
var total = 0.0
for vote in votes {
total += vote
}
let votesTotal = Double(votes.count)
var average = total/votesTotal
return average
}
average[votes]
我怎么在这里所说的平均获得平均?
How do I call the average here to get the average?
推荐答案
您应该使用减少()方法来总结您的数组如下:
You should use the reduce() method to sum your array as follow:
let votes:[Double] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let votesAvg = votes.reduce(0, combine: +) / Double(votes.count)
println( votesAvg ) // "5.5"
更新:
您还可以扩展延伸斯威夫特 _ArrayType 议定书阵列的只是一个特定类型返回其元素平均如下:
You can also extend just a specific type of array extending Swift _ArrayType Protocol to return its elements average as follow:
extension _ArrayType where Generator.Element == Int {
var total: Int {
guard !isEmpty else { return 0 }
return reduce(0, combine: +)
}
var average: Double {
return Double(total)/Double(count)
}
}
extension _ArrayType where Generator.Element == Double {
var total: Double {
guard !isEmpty else { return 0 }
return reduce(0, combine: +)
}
var average: Double {
guard !isEmpty else { return 0 }
return total / Double(count)
}
}
这篇关于制作阵列斯威夫特我的函数计算平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文