SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Exercises
Question:11 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.