arrays - 二维数组中的单个元素的数学运算 - Swift

标签 arrays swift math swift3 operation

我正在尝试对结合一维数组 (mod) 的二维数组 (testArray) 的各个元素执行不同的数学运算。我有以下用于生成单个变量的方法,但无法弄清楚如何将这些值返回到新的二维数组中。 swift 3.0.2。

let testArray: [[Double]] =
    [[0,100,20.1],
     [1,99,19.2],
     [3,98,18.2],
     [5,97,17.3],
     [7,96,16.4],
     [9,95,15.5]]

let mod: [Double] = [0,5,7,14,20,22]

//Math operations on the two above arrays
for var x in 0..<testArray.count {
    var result1 = Double(testArray[x][0])
    var result2 = Double(testArray[x][1] + mod[x])
    var result3 = Double(testArray[x][2] - mod[x])
    print(result1,result2,result3)
}

//output is as follows:
0.0 100.0 20.1
1.0 104.0 14.2
3.0 105.0 11.2
5.0 111.0 3.3
7.0 116.0 -3.6
9.0 117.0 -6.5

//how do I get the same numbers into a new 2D array as follows:
[[0.0,100.0,20.1],
 [1.0,104.0,14.2],
 [3.0,105.0,11.2],
 [5.0,111.0,3.3],
 [7.0,116.0,-3.6],
 [9.0,117.0,-6.5]]

最佳答案

可以这么简单,

var anotherArray: [[Double]] = []
for x in 0..<testArray.count {
    let result1 = Double(testArray[x][0])
    let result2 = Double(testArray[x][1] + mod[x])
    let result3 = Double(testArray[x][2] - mod[x])
    anotherArray.append([result1, result2, result3])
}
print(anotherArray)

关于arrays - 二维数组中的单个元素的数学运算 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55508156/

相关文章:

c++ - 编译时的浮点运算

javascript - 如何将 HTML 无序列表转换为 jQuery 自动完成?

algorithm - 检查一组随机 16 个数字的中位数的检查次数

python - 3D 数组中一个轴上的滚动平均值

regex - 如何在 swift 项目中查找非本地化字符串

ios - Swift:UITableView 未使用 reload() 正确更新数据

ios - 在 iOS 上测试 AdMob

math - 为什么 CRC 32 生成器不能被 11 整除?

javascript - 匹配对象数组中的 2 个属性值,并根据第三个属性值过滤匹配

java - 如何使用System.arraycopy优化这个方法?