Search code examples
javapi

Raise Pi to -4 to 4


In this homework i have to raise the number pi from -4 to 4. I did it well from 0 to 4 but in the negative numbers i have problems. I know that the problem is that when the number is negative no matter what , the program do 1/pi, but i cant figure out how to resolve this.

import acm.program.ConsoleProgram;
public class raisRealToPower2 extends ConsoleProgram {

    public void run () {
       double n = 3.14159;
       for (int k = -4; k < 4; k++ ) {
           println (n + " exp " + k + " is " +  (RaisePi (n, k)));
       }     
    }       

    private double RaisePi (double n, double k){
       double total = n;
       for (double i=1; i<k; i++) {
           total*=n; 
       }

       if (k>0){
           return total; 
        } else if (k==0) {
           return 1.0 ;
        } else {
           return 1/total;      
        }
    }
}

Solution

  • I would add a line at the start

    if(k < 0) return 1/raisePi(n, -k);