计算任何指数的幂(负数或正数) [英] Calculate the power of any exponent (negative or positive)

查看:444
本文介绍了计算任何指数的幂(负数或正数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算结果,给定任何指数(负数或正数)和整数类型的基数。我正在使用递归:

I want to calculate the result, given any exponent (negative or positive) and a base of type integer. I am using recursion:

public static double hoch(double basis, int exponent) {
    if (exponent > 0) {
        return (basis * hoch(basis, exponent - 1));
    } else if (exponent < 0) {
        return ((1 / (basis * hoch(basis, exponent + 1))));
    } else {
        return 1;
    }
}

如果指数为负,则返回1.0,但这是错误的。对于例如hoch(2,-2)它应该是0.25。什么可能是错的?

If exponent is negative 1.0 is returned but that is wrong. For e.g. hoch(2,-2) it should be 0.25. Any ideas what could be wrong?

推荐答案

 }else if(exponent < 0){
         return ((1/(basis*hoch(basis, exponent+1))))

 }else if(exponent < 0){
        return (1/hoch(basis, -exponent));

这篇关于计算任何指数的幂(负数或正数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆