x ^ 0 + x ^ 1 + x ^ 2 +… x ^ n을 표시 한 다음 x ^ n의 계산 된 값을 표시하는 재귀 메서드를 어떻게 작성합니까?

Nov 17 2020

재귀 적 방법을 작성하여 계산하고 싶습니다.

x ^ 0 + x ^ 1 + x ^ 2 + ... x ^ n

그런 다음 계산 된 x ^ n 예의 값을 표시하고 싶습니다.

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);
        
    }
    
}

답변

1 WJS Nov 18 2020 at 02:48

대안으로 이것을 시도하십시오. 핵심은 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

당신이 당신의 멱급수 디스플레이에 부동 소수점 값을 원하지 않는 경우, 단지 캐스트 vint

AzizSonawalla Nov 18 2020 at 01:24

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
  }
}
lierwu Nov 18 2020 at 01:25

내 말은, 거기에 도달하면 번호를 인쇄합니다.

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
            } 
        }
        
    }
DowenyTony Nov 18 2020 at 01:44

public class Demo {

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)));

}

}