怎么用递归求幂值 JAVA
来源:百度知道 编辑:UC知道 时间:2024/05/18 05:52:05
要用递归!
不能用MATH.POW()
import java.util.Scanner;
public class test005 {
double myPow(double x, int y) {
double pow = 0;
if (y > 0) {
pow = x * myPow(x, y - 1);// 2,3//2*2,3-1
}
if (y < 0) {
pow = 1 / x * myPow(x, y + 1);
}
if (y == 0) {
pow = 1;
}
return pow;
}
void count() {
System.out.println("please input base number and index number");
double base = new Scanner(System.in).nextInt();
int index = new Scanner(System.in).nextInt();
double result = myPow(base, index);
System.out.println(result);
}
public static void main(String[] s) {
new test005().count();
}
}
public double myPow(double x,int y)
{
if (y==0) {
return 1;
}
if (y>0) {
return x=x*myPow(x,--y);
}
else
{
return x=1/x*myPow(x,++y);