如何在 Swift 中以 3 的幂提升 int 数组中的所有元素? [英] How can I raise all the elements in an int array by a power of 3 in Swift?

查看:28
本文介绍了如何在 Swift 中以 3 的幂提升 int 数组中的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如说我有数组:

let nums = [1, 2, 3, 4, 5, 6]

我想输出一个包含多维数据集值的新数组:[1, 8, 27, 64, 125, 216]

I would like to output a new array with the cube values: [1, 8, 27, 64, 125, 216]

我必须使用循环吗?

推荐答案

您可以使用 ma​​p()pow() 在一起:

You can use map() and pow() together:

import Foundation

let nums = [1, 2, 3, 4, 5, 6]
let cubes = nums.map { Int(pow(Double($0), 3)) }
let raisedBySix = nums.map { Int(pow(Double($0), 6)) }
print(cubes)       // [1, 8, 27, 64, 125, 216]
print(raisedBySix) // [1, 64, 729, 4096, 15625, 46656]

这篇关于如何在 Swift 中以 3 的幂提升 int 数组中的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆