在 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)
如果您不需要 Kotlin 多平台支持,Java 标准库有Math.cbrt(),可以从 Kotlin 安全地调用它。
val x: Double = Math.cbrt(125.0) // 5.0
Run Code Online (Sandbox Code Playgroud)
无需使用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)
| 归档时间: |
|
| 查看次数: |
2153 次 |
| 最近记录: |