且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

二元运算符“/"不能应用于两个“双"操作数

更新时间:2021-11-10 21:35:51

这个错误有点误导.

在第一组代码中,array2被隐式声明为一个Int的数组.因此,任何为 array2 的索引赋值的尝试都需要一个 Int 值.

In the first set of code, array2 is implicitly declared as an array of Int. So any attempt to assign a value to an index of array2 will require an Int value.

问题是 Double(value)/2.0 导致 Double 值,而不是 Int.因此,编译器正在寻找返回 Int/ 版本.该版本需要两个 Int 参数.由于您提供了两个 Double 参数,因此您会收到问题中提到的错误.

The problem is that Double(value) / 2.0 results in a Double value, not an Int. So the compiler is looking for a version of / that returns an Int. And that version expects two Int parameters. Since you are supplying two Double parameters, you get the error mentioned in your question.

解决方案是将结果转换为 Int 或使用两个 Int 参数到 /.

The solution is to either cast the result to an Int or use two Int parameters to /.

var array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = Int(Double(value) / 2.0) // cast to Int
}

var array2 = [8, 7, 19, 20]

for (index, value) in array2.enumerated() {
    array2[index] = value / 2 // Use two Int
}

在这种情况下,结果将是相同的.8 将替换为 4.7 将替换为 3

The result will be the same in this case. 8 will be replaced with 4. 7 will be replaced with 3, etc.

第二组代码按原样工作,因为您将数组声明为用 Double 填充,因此所有内容都与正确的类型匹配.

The second set of code works as-is because you declare the array to be filled with Double so everything matches up with the correct type.