让我的函数计算数组的平均值Swift

myzjeezk  于 2023-10-15  发布在  Swift
关注(0)|答案(7)|浏览(135)

我希望我的函数计算Double类型数组的平均值。这个数组叫做“votes”。现在,我有10个数字。
当我调用average function来获取数组投票的平均值时,它不起作用。
下面是我的代码:

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]

我如何调用平均值来得到平均值?

628mspwn

628mspwn1#

您应该使用reduce方法对序列元素求和,如下所示:

Xcode Xcode 10.2+ · Swift 5以上版本

extension Sequence where Element: AdditiveArithmetic {
    /// Returns the total sum of all elements in the sequence
    func sum() -> Element { reduce(.zero, +) }
}
extension Collection where Element: BinaryInteger {
    /// Returns the average of all elements in the array
    func average() -> Element { isEmpty ? .zero : sum() / Element(count) }
    /// Returns the average of all elements in the array as Floating Point type
    func average<T: FloatingPoint>() -> T { isEmpty ? .zero : T(sum()) / T(count) }
}
extension Collection where Element: BinaryFloatingPoint {
    /// Returns the average of all elements in the array
    func average() -> Element { isEmpty ? .zero : sum() / Element(count) }
}
let votes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let votesTotal = votes.sum()                       // 55
let votesAverage = votes.average()                 // 5
let votesDoubleAverage: Double = votes.average()   // 5.5

如果你需要处理Decimal类型的总和,它已经被AdditiveArithmetic协议扩展方法覆盖了,所以你只需要实现平均值:

extension Collection where Element == Decimal {
    func average() -> Decimal { isEmpty ? .zero : sum() / Decimal(count) }
}

如果你需要对自定义结构的某个属性求和,我们可以扩展Sequence并创建一个方法,该方法以KeyPath作为参数来计算其总和:

extension Sequence  {
    func sum<T: AdditiveArithmetic>(_ predicate: (Element) -> T) -> T {
        reduce(.zero) { $0 + predicate($1) }
    }
}

使用方法:

struct User {
    let name: String
    let age: Int
}

let users: [User] = [
    .init(name: "Steve", age: 45),
    .init(name: "Tim", age: 50)]

let ageSum = users.sum(\.age) // 95

并扩展集合以计算其平均值:

extension Collection {
    func average<T: BinaryInteger>(_ predicate: (Element) -> T) -> T {
        sum(predicate) / T(count)
    }
    func average<T: BinaryInteger, F: BinaryFloatingPoint>(_ predicate: (Element) -> T) -> F {
        F(sum(predicate)) / F(count)
    }
    func average<T: BinaryFloatingPoint>(_ predicate: (Element) -> T) -> T {
        sum(predicate) / T(count)
    }
    func average(_ predicate: (Element) -> Decimal) -> Decimal {
        sum(predicate) / Decimal(count)
    }
}

使用方法:

let ageAvg = users.average(\.age)                 // 47
let ageAvgDouble: Double = users.average(\.age)   // 47.5
41ik7eoe

41ik7eoe2#

你的代码中有一些错误:

//You have to set the array-type to Double. Because otherwise Swift thinks that you need an Int-array
var votes:[Double] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

func average(nums: [Double]) -> Double {

    var total = 0.0
    //use the parameter-array instead of the global variable votes
    for vote in nums{
        total += Double(vote)
    }

    let votesTotal = Double(nums.count)
    var average = total/votesTotal
    return average
}

var theAverage = average(votes)
w6lpcovy

w6lpcovy3#

一个小的一行程序,使用老式的KVC在Swift中翻译:

let average = (votes as NSArray).value(forKeyPath: "@avg.floatValue")

你也可以有总和:

let sum = (votes as NSArray).value(forKeyPath: "@sum.floatValue")

更多关于这颗被遗忘的宝石:https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/CollectionOperators.html

of1yzvn4

of1yzvn44#

如果需要的话,使用过滤器进行简单的平均(Swift 4.2):

let items: [Double] = [0,10,15]
func average(nums: [Double]) -> Double {
    let sum = nums.reduce((total: 0, elements: 0)) { (sum, item) -> (total: Double, elements: Double) in
        var result = sum
        if item > 0 { // example for filter
            result.total += item
            result.elements += 1
        }

        return result
    }

    return sum.elements > 0 ? sum.total / sum.elements : 0
}
let theAvarage = average(nums: items)
yftpprvb

yftpprvb5#

我有一组在更新函数中创建的信号,为了获得移动平均值,我使用此函数计算由移动平均值周期定义的窗口内的平均值。由于我的目标是组装一组包含平均值的新信号,因此我将丢弃原始信号集的信号。对于那些希望在更新函数中使用移动平均值的人来说,这是一个很好的解决方案,例如在SKScene中。

func movingAvarage(_ period: Int) -> Double? {
  if signalSet.count >= period {
   let window = signalSet.suffix(period)
   let mean = (window.reduce(0, +)) / Double(period)
   signalSet = signalSet.dropLast(period)
   return mean
  }
  return nil
}
pgky5nke

pgky5nke6#

Swift 4.2

对于纯粹的优雅简单,我爱:

// 1. Calls #3
func average <T> (_ values: T...) -> T where T: FloatingPoint
{
    return sum(values) / T(values.count)
}

当我们在这里的时候,其他不错的基于reduce的操作:

// 2. Unnecessary, but I appreciate variadic params. Also calls #3.
func sum <T> (_ values: T...) -> T where T: FloatingPoint
{
    return sum(values)
}

// 3.
func sum <T> (_ values: [T]) -> T where T: FloatingPoint
{
    return values.reduce(0, +)
}

图片来源:Adrian Houdart的MathKit,基本上没有变化。

  • 可爱的更新:*

我在The Swift Programming Language中找到了以下内容:
下面的示例计算任意长度的数字列表的算术平均值(也称为平均值):

func arithmeticMean(_ numbers: Double...) -> Double {
   var total: Double = 0
   for number in numbers {
       total += number
   }
   return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers
1sbrub3j

1sbrub3j7#

将这些扩展添加到Array将计算Int和FloatingPoint值的平均值:

extension Array where Element: BinaryInteger {

  var average: Element? {
      guard let elementCount = Element(exactly: count) else { return nil }
      return reduce(0) { $0 + $1 } / elementCount
  }
}

extension Array where Element: FloatingPoint {

var average: Element? {
      guard let elementCount = Element(exactly: count) else { return nil }
      return reduce(0) { $0 + $1 } / elementCount
  }
}

相关问题