n java递归_使用Java中的递归将x提高到n

可以使用递归来计算数字的幂。这里的数字是x,并乘幂n。

演示此过程的程序如下:

示例public class Demo {

static double pow(double x, int n) {

if (n != 0)

return (x * pow(x, n - 1));

else

return 1;

}

public static void main(String[] args) {

System.out.println("7 to the power 3 is " + pow(7, 3));

System.out.println("4 to the power 1 is " + pow(4, 1));

System.out.println("9 to the power 0 is " + pow(9, 0));

}

}

输出结果7 to the power 3 is 343.0

4 to the power 1 is 4.0

9 to the power 0 is 1.0

现在让我们了解上面的程序。

该方法pow()计算x的幂n。如果n不为0,则递归调用自身并返回x * pow(x,n-1)。如果n为0,则返回1。演示此代码段如下:static double pow(double x, int n) {

if (n != 0)

return (x * pow(x, n - 1));

else

return 1;

}

在中main(),pow()使用不同的值调用该方法。演示此代码段如下:public static void main(String[] args) {

System.out.println("7 to the power 3 is " + pow(7, 3));

System.out.println("4 to the power 1 is " + pow(4, 1));

System.out.println("9 to the power 0 is " + pow(9, 0));

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值