func avg(numbers: Int...) -> Double {
var sum = 0;
var i = 0;
for number in numbers {
sum += number;
++i;
}
return sum / i;
}
avg(42, 597, 12);
The line return sum / i
results in an error Could not find an overload for '/' that accepts the supplied arguments.
What am I supposed to be doing here?
You can do that quite simply do that by adding a ". 0" on the end of the Integer you want to convert.
If either operand is a double, you'll get floating point arithmetic. If both operands are ints, you'll get integer arithmetic. 3.5/3 is double/int, so you get a double.
To divide a value by another in Swift, use the division operator (/).
Swift doesn't implicitly convert between value types, like we've been used to, so any product of your sum
and i
variables will have the same type they do. You've let them implicitly be defined as Int
, so you'll need to cast their type during the final computation, like so:
return Double(sum) / Double(i)
If you want to return a Double you should deal with Doubles in your function. Change sum and i to Doubles (0.0 vs 0) and convert each number to a double. Like this:
func avg(numbers: Int...) -> Double {
var sum = 0.0; //now implicitly a double
var i = 0.0;
for number in numbers {
sum += Double(number); //converts number to a double and adds it to sum.
++i;
}
return sum / i;
}
avg(42, 597, 12);
Integer and Floating-Point Conversion
Conversions between integer and floating-point numeric types must be made explicit:
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to be of type Double
Here, the value of the constant three is used to create a new value of type Double, so that both sides of the addition are of the same type. Without this conversion in place, the addition would not be allowed.
The reverse is also true for floating-point to integer conversion, in that an integer type can be initialized with a Double or Float value:
let integerPi = Int(pi)
// integerPi equals 3, and is inferred to be of type Int
Floating-point values are always truncated when used to initialize a new integer value in this way. This means that 4.75 becomes 4, and -3.9 becomes -3.
Here's an improved answer, using the friendly power of closures:
func avg(numbers: Int...) -> Double {
return Double(numbers.reduce(0, +)) / Double(numbers.count)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With