Reputation: 3527
In swift I'm trying to write a method to calculate the average. Using the method below if i type average(5,10,15) I get infinity displayed in the swift-playforund
func average(numbers: Int...) -> Double {
var sum = 0
var count = 0
for number in numbers {
sum += number
}
var ave : Double = Double(sum) / Double(count)
return ave
}
Upvotes: 9
Views: 23213
Reputation: 3401
import Accelerate
let avg = vDSP.mean(array)
This will be at least 50x faster than all other solutions posted so far.
Upvotes: 11
Reputation: 11173
While others have already pointed out the missing count variable, it is worth noting that you can do the average even more elegantly by using closures as follows:
func averagec(numbers:Int...) -> Double {
return Double(numbers.reduce(0,combine:+))/Double(numbers.count)
}
Edited for Swift 4:-
func averagec(numbers:Int...) -> Double {
return Double(numbers.reduce(0,+))/Double(numbers.count)
}
Upvotes: 21
Reputation: 10896
Swift 3, functional style
func average(numbers: Int...) -> Double {
assert(numbers.count > 0)
return numbers.reduce(0, {$0 + Double($1)})/Double(numbers.count)
}
Upvotes: 1
Reputation: 7973
check this method.
func averageOf(numbers:Int...)->Float{
var sum = 0
for number in numbers{
sum += number
}
return Float(sum)/Float(numbers.count)
}
averageOf(20,10,30)
Upvotes: 0
Reputation: 8323
It's so much easier with just a straightforward call to reduce
:
let array = [1.0,2.0,3.0]
var average = array.reduce(0.0) {
return $0 + $1/Double(array.count)
}
// average = 2.0
Upvotes: 35
Reputation: 864
Here's what I did:
func getAverage(nums: Double...) ->Double
{
var temp = 0.0
for num in nums
{
temp+=num
}
let div = Double(nums.count)
var average = temp/div
return average
}
getAverage(21,34.5,28,79)
Note that I'm accepting Doubles as input, not just Ints. I'm being a little verbose at the end, but I was trying for readable code. I probably could have just returned:
return temp/Double(nums.count)
at the end and saved a few lines of code.
Upvotes: 1
Reputation: 45466
You're getting infinity because count
is always 0 - it's never incremented. So the ave
variable is always going to be equal to some number over 0, which is a divide by zero error.
Either use countElements(numbers)
or increment count on each iteration through the loop.
Upvotes: 1
Reputation: 17460
You can use the count property of the array:
func average(numbers: Int...) -> Double {
var sum = 0
for number in numbers {
sum += number
}
var ave : Double = Double(sum) / Double(numbers.count)
return ave
}
Upvotes: 23
Reputation: 47099
Just write count = count +1
in your for
loop.
Such like,,,
.
.
.
for number in numbers
{
sum += number
count = count +1
}
.
.
And now function by
var avg:Double = average(5,10,15)
println(avg)
Upvotes: 3