如何计算Kotlin中的立方根?

如何计算Kotlin中的立方根?,kotlin,Kotlin,在kotlin有一个内部的数学库,我只找到平方根,但没有立方根 导入kotlin.math.sqrt 导入kotlin.math.pow 有趣的公式(a:Int):双倍{ //无效 //rs=a.pow(1/3) //作用 复述 } 趣味主线(args:Array){ val calc=公式(9) } 如果您不需要Kotlin多平台支持,Java标准库有,可以从Kotlin安全地调用 val x: Double = Math.cbrt(125.0) // 5.0 无需使用Java库,只需使用

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

导入kotlin.math.sqrt
导入kotlin.math.pow
有趣的公式(a:Int):双倍{
//无效
//rs=a.pow(1/3)
//作用
复述
}
趣味主线(args:Array){
val calc=公式(9)
}

如果您不需要Kotlin多平台支持,Java标准库有,可以从Kotlin安全地调用

val x: Double = Math.cbrt(125.0) // 5.0

无需使用Java库,只需使用Kotlin一个:

import kotlin.math.pow

fun formula(a:Int):Double {
    return a.toDouble().pow(1/3.toDouble())
}
刚刚测试过:

println(formula(9)) //2.080083823051904

println(formula(27)) //3.0
/** *程序:Kotlin程序计算125的立方根 *日期:2021年6月4日星期二 *@作者:ANKUR SAXENA *平台:Windows10Pro/x64/Kotlin v1.4.31/VS代码 */ //多维数据集根逻辑,var result=(Math.cbrt(num)) //程序启动 //主要功能 趣味主线(args:Array) { //声明变量 var num:Int=125 //打印值 println(“数字的值:$num\n”) //计算立方根 var cubeRoot:Double=(Math.cbrt(num.toDouble()) //打印立方根 println(“\n$num的多维数据集根是:$cubeRoot\n”) } //程序结束
//将此文件另存为“CubeRoot1.kt”
//编译:$kotlinc CubeRoot1.kt[点击回车键]
//执行:$kotlin CubeRoot1Kt[点击回车键]
输出:

Value of the number: 125 Cube root of 125 is: 5.0 数字的值:125 125的立方根为:5.0
a.pow(1.0/3.0))
对我来说很好。因为它以“4.9999999”结尾。见:@Todd good point;我只使用OP的例子9对它进行了测试,得到了相同的结果。@royer您可以在不使用Java库的情况下实现这一点。检查我的答案:)在这种情况下,您可能还应该使用
pow
而不是
Math.pow
@Louis tankyou@royer不客气。如果这个答案有帮助,请接受它,这样每个人都能从中受益。:)哦,范坦斯蒂克,你呢 /** * Program: Kotlin program to calculate the cube root of 125 * Date: Tue, 6-4-2021 * @author: ANKUR SAXENA * Platform: Windows 10 Pro/x64/Kotlin v1.4.31/VS Code */ // cube root logic, var result = (Math.cbrt(num)) // program start // main function fun main (args: Array) { // declare variables var num: Int = 125 // print value println ("Value of the number: $num\n") // calculate cube root var cubeRoot: Double = (Math.cbrt(num.toDouble())) // print cube root println ("\nCube root of $num is: $cubeRoot\n") } // program end Value of the number: 125 Cube root of 125 is: 5.0