简体   繁体   English

使用Swift将int分为双打

[英]Divide ints into doubles using Swift

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. return sum / i导致错误Could not find an overload for '/' that accepts the supplied arguments.

What am I supposed to be doing here? 我应该在这做什么?

If you want to return a Double you should deal with Doubles in your function. 如果你想要返回一个Double,你应该在你的函数中处理双打。 Change sum and i to Doubles (0.0 vs 0) and convert each number to a double. 将sum和i更改为Doubles(0.0 vs 0)并将每个数字转换为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. 这里,常量3的值用于创建Double类型的新值,以便添加的两侧具有相同的类型。 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: 对于浮点数到整数转换,反之亦然,因为可以使用Double或Float值初始化整数类型:

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. 这意味着4.75变为4,-3.9变为-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)
}

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. Swift不会像我们习惯的那样在值类型之间隐式转换,因此sumi变量的任何产品都将具有相同的类型。 You've let them implicitly be defined as Int , so you'll need to cast their type during the final computation, like so: 你已经将它们隐式地定义为Int ,所以你需要在最终计算期间转换它们的类型,如下所示:

return Double(sum) / Double(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM