如何编写递归方法来显示x^0+x^1+x^2+然后显示x^n的计算值?

i2byvkas  于 2021-07-11  发布在  Java
关注(0)|答案(4)|浏览(302)

我想写一个递归方法来计算
x^0+x^1+x^2+。。。x^n个
然后我想显示计算的x^n ex的值:
n=3和x=3输出应为:1+3+9+27
我有这样的代码来计算递归方法,但是如何使用该方法来打印每个迭代?
我的代码是:

public static double compute(int n, int x){

    if(n == 0){
        return 1;
    }
    else{

        return Math.pow(x , n) + compute(x , n-1);

    }

}
huwehgph

huwehgph1#

试试这个。关键是保存 Math.pow 在打印它之前,在调用堆栈上。这样,当方法展开时,术语的顺序就正确了。

double v = compute(3,3);
System.out.println("\nv = " + v);

public static double compute(int n, int x) {
    double v;
    if (n == 0) {
       System.out.print(1.);
       return 1;
   }
   // save a copy of the power method for printout
   double r = compute(n-1,x)+ (v = Math.pow(x,n));
   System.out.print(" + " + v);
   return r;
}

印刷品

1.0 + 3.0 + 9.0 + 27.0
v = 40.0

如果您不想在幂级数显示中使用浮点值,那么只需强制转换 v 到一个 int

k4emjkb1

k4emjkb12#

你只需要打个电话 System.out.print() 每次递归调用时:

public static double compute(int n, int x) {
  if (n == 0) {
    System.out.print("1");  // print 1 (no "+" here because it's the last call)
    return 1;
  } else {
    double currVal = Math.pow(x, n);   // value for the current x and n
    System.out.print(String.valueOf(currVal) + " + ");  // print currVal with "+"
    return currVal + compute(n - 1, x);  // make recursive call
  }
}
fhity93d

fhity93d3#

我的意思是,当你到达那里时,你打印号码:

public static double compute(int n, int x){

    if(n == 0){
        System.out.print(1);//It's 1...
        return 1;
    }
    else{
        int number = (int)Math.pow(x , n);
        System.out.print(number + "+");//since n is not 0, there must be data printed after this 
        return number + compute(n - 1 , x);
    }

}

或者如果要从最小到最大打印:

public static double compute(int n, int x){    
        if(n == 0){
            System.out.print(1);//It's 1...
            return 1;
        }
        else{
            int number = (int)Math.pow(x , n);
            try {//needed for the finally statement
                return number + compute(n - 1 , x);
            }finally {//finaly block will be executed even after return
                System.out.print("+" + number);//since n is not 0, there must be data printed before this
            } 
        }

    }
ujv3wf0j

ujv3wf0j4#

公开课演示{

public static StringBuilder stringBuilder = new StringBuilder();

public static double compute(int n, int x) {

    if (n == 0) {
        stringBuilder.insert(0, x + "^" + n);
        return 1;
    } else {
        stringBuilder.insert(0, " + " + x + "^" + n);
        return Math.pow(x, n) + compute(n - 1, x);
    }
}

public static void main(String[] args) {
    System.out.println(stringBuilder.append(" = ").append(compute(5, 2)));

}

}

相关问题