kotlin 尾递归
Given two numbers (base, power), we have to calculate base to the power of power.
鉴于两个数字( 基地 , 电力 ),我们要计算的基础 ,以电力的电能。
Example:
例:
Input:
base = 2
power = 3
Output:
8
该程序在Kotlin中使用递归来计算数字的幂 (Program to calculate the power of a number using recursion in Kotlin)
package com.includehelp.basic
import java.util.*
//function to calculate power using recursion
fun calPower(baseValue: Int, powerValue: Int): Int {
return if (powerValue != 0) baseValue * calPower(baseValue, powerValue - 1) else 1
}
//Main Function entry Point of Program
fun main(args: Array<String>) {
//Input Stream
val scanner = Scanner(System.`in`)
//input Base integer number
print("Enter Base Number : ")
val base: Int = scanner.nextInt()
//input Power integer number
print("Enter Power Number : ")
val power: Int = scanner.nextInt()
//Call function to Calculate Power using recursion
val res = calPower(base,power)
//Print Result
println("$base^$power = $res")
}
Output
输出量
Run 1:
Enter Base Number : 5
Enter Power Number : 3
5^3 = 125
-------
Run 2:
Enter Base Number : 6
Enter Power Number : 4
6^4 = 1296
-------
Run 3:
Enter Base Number : 7
Enter Power Number : 0
7^0 = 1
翻译自: https://www.includehelp.com/kotlin/calculate-the-power-of-a-number-using-recursion.aspx
kotlin 尾递归