0

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

Edited by Yutxz: n/a

1
Contributor
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Yutxz
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;
}
}
}

Edited by Yutxz: n/a

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;
    }
    }
    }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.