如何在 Kotlin 中计算立方根?

roy*_*yer 4 kotlin

在 kotlin 中有一个内部数学库,我只找到平方根,但没有立方根。

立方根

import kotlin.math.sqrt
import kotlin.math.pow

fun Formule(a:Int):Double{
    //no working
    //rs = a.pow(1/3)
    //function
    retun rs
}

fun main(args: Array<String>){
    val calc = Formule(9)
}
Run Code Online (Sandbox Code Playgroud)

Tod*_*odd 5

如果您不需要 Kotlin 多平台支持,Java 标准库有Math.cbrt(),可以从 Kotlin 安全地调用它。

val x: Double = Math.cbrt(125.0) // 5.0
Run Code Online (Sandbox Code Playgroud)


Lou*_*uis 5

无需使用Java 库,只需使用Kotlin

import kotlin.math.pow

fun formula(a:Int):Double {
    return a.toDouble().pow(1/3.toDouble())
}
Run Code Online (Sandbox Code Playgroud)

刚刚测试了一下:

println(formula(9)) //2.080083823051904

println(formula(27)) //3.0
Run Code Online (Sandbox Code Playgroud)