kotlin 尾递归_Kotlin程序使用递归计算数字的幂

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 尾递归

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值