Modify your pow method from Exercise 4 to make a new method called pow2 that uses the type double for the first parameter and that works correctly for negative numbers. For example, the call pow2(–4.0, 3) should return –4.0 * –4.0 * –4.0, or –64.0, and the call pow2(4.0, –2) should return 1 / 16, or 0.0625.
Program:
public class Ch04Ex11
{
public static void main(String[] args)
{
System.out.println("pow2(-4.0, 3): " + pow2(-4.0, 3));
System.out.println("pow2(4.0, -2): " + pow2(4.0, -2));
}
public static double pow2(double base, int exponent)
{
double result = 1;
for (int i = 0; i < Math.abs(exponent); i++)
{
result *= base;
}
if(exponent >= 0)
return result;
else
return (1.0 / result);
}
}
Output:
pow2(-4.0, 3): -64.0
pow2(4.0, -2): 0.0625