954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Recursive Help

I received the error "possible loss of precision" on the last line of my code. Is it not possible to return a double?

My instructions were to create a program, called power, that took a double (x) and raised it to an integer (n) power.

package power;

/**
 *
 * @author Josh
 */
public class Main {

public static void main (String[] args) {
power (4.5, 5);
// invoke power
}

public static int power (double x, int n)
{
if (x == 0) {
return 0;
// if x = 0, then return 0 and terminate program
} else {
int recurse = power (x, n-1);
double result = x * recurse;
// recursive x^n
return result; 
}
}
}
Yutxz
Light Poster
36 posts since Dec 2007
Reputation Points: 10
Solved Threads: 0
 

*Revised to accommodate for other errors.
I'm trying to return a double and the method result is a double, so why do I receive an error?

package power;

/**
 *
 * @author Josh
 */
public class Main {

public static void main (String[] args) {
power (4.5, 5);
// invoke power
}

public static int power (double x, int n)
{
if (n != 0) {
// if n does not equal 0, then initiate recursion
int recurse = power (x, n-1);
double result = x * recurse;
// recursive x^n
return result; 
    } else{
// If n equals 1, than the result is 1 and the program terminates
    return 1;
}
}
}
Yutxz
Light Poster
36 posts since Dec 2007
Reputation Points: 10
Solved Threads: 0
 

Oh wow, I'm an idiot. I had my method defined as an int. DUH!!

package power;
     
    /**
     *
     * @author Josh
     */
    public class Main {
     
    public static void main (String[] args) {
    power (4.5, 5);
    // invoke power
    }
     
    public static double power (double x, int n)
    {
    if (n != 0) {
    // if n does not equal 0, then initiate recursion
    double recurse = power (x, n-1);
    double result = x * recurse;
    // recursive x^n
    return result;
    } else{
    // If n equals 1, than the result is 1 and the program terminates
    return 1;
    }
    }
    }
Yutxz
Light Poster
36 posts since Dec 2007
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: