如何编写可以用Java计算能力的函数.无循环 [英] How to write a function that can calculate power in Java. No loops

查看:62
本文介绍了如何编写可以用Java计算能力的函数.无循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试用Java编写一个简单的函数,该函数可以不使用循环就可以计算出n次方的数字.
然后,我发现 Math.pow(a,b)类...或方法仍然无法区分两者,理论上不太好.所以我写了这个..

I've been trying to write a simple function in Java that can calculate a number to the nth power without using loops.
I then found the Math.pow(a, b) class... or method still can't distinguish the two am not so good with theory. So i wrote this..

public static void main(String[] args) {

    int a = 2;

    int b = 31;

    System.out.println(Math.pow(a, b));

    }

然后我想不使用循环就制作自己的 Math.pow ,我希望它看起来比循环更简单,例如使用某种类型的 Repeat ,我做了很多事情直到我遇到使用 StringUtils.repeat
尝试过的 commons-lang3 程序包为止到目前为止,我认为这是语法:-

Then i wanted to make my own Math.pow without using loops i wanted it to look more simple than loops, like using some type of Repeat I made a lot of research till i came across the commons-lang3 package i tried using StringUtils.repeat
So far I think this is the Syntax:-

public static String repeat(String str, int repeat)
    StringUtils.repeat("ab", 2);

我遇到过过去24小时问题 StringUtils.repeat(String str,int 2); 重复字符串,而不是放置,数字或计算.
我可以做些什么来克服这个问题,或者还有其他更好的方法来创建一个计算幂的函数吗?
不使用循环或Math.pow

The problem i've been facing the past 24hrs or more is that StringUtils.repeat(String str, int 2); repeats strings not out puts or numbers or calculations.
Is there anything i can do to overcome this or is there any other better approach to creating a function that calculates powers?
without using loops or Math.pow

这可能很有趣,但是花了我一段时间才发现 StringUtils.repeat 仅重复字符串,这就是我试图克服的方法.万一有帮助

This might be funny but it took me while to figure out that StringUtils.repeat only repeats strings this is how i tried to overcome it. incase it helps

 public static int repeat(int cal, int repeat){
     cal = 2+2;
     int result = StringUtils.repeat(cal,2);
     return result;
}  

我不能使用递归,也许像这样

can i not use recursion maybe some thing like this

public static RepeatThis(String a)
{
     System.out.println(a);
     RepeatThis(a);
} 

只是尝试理解dept中的Java,感谢您的所有评论,即使存在语法错误,只要理解的逻辑对我也很有益:)

推荐答案

尝试递归:

int pow(int base, int power){
    if(power == 0) return 1;
    return base * pow(base, --power);
}

这篇关于如何编写可以用Java计算能力的函数.无循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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