Thursday, 4 December 2014

// The "MathMethodExamples1" class.  Page 72-73.
// (from the Carter book)

// Examples 1, 2 and 3.  How to use Math.abs, Math.sqrt
// and Math.pow (Math methods) to do different calculations.
// Find the return value of each type of calculation.
// Example 1: Math.abs returns any type except for boolean.
// Example 2: Math.sqrt returns the square root of the given positive value.
// Example 3: Math.pow returns the given positive value to its given power.

public class MathMethodExamples1
{
    public static void main (String[] args)
    {
        // Example 1--Math.abs:
        // Part (1a):  (returning an int positive value)
        System.out.println ("Math.abs(-4) = " + Math.abs (-4));
        // Part (1b):  (returning a double value)
        System.out.println ("Math.abs (2.7) = " + Math.abs (2.7));
        
        // Part (1c):  (returning an exponent form of the value)
        System.out.println ("Math.abs (-8.0e-4) = " + Math.abs (-8.2e-4));

        // Part (1d):  (returning a long value)
        System.out.println ("Math.abs (-456) = " + Math.abs (-456));
        System.out.println ();

        // Example 2 -- Math.sqrt:
        // Part (2a):  (returning a square root -- as a double)
        System.out.println ("Math.sqrt (4) = " + Math.sqrt (4));

        // Part (2b):  (returning a square root -- as a double)
        System.out.println ("Math.sqrt (7.0) = " + Math.sqrt (7.0));

        // Part (2c):  (not returning a square root of a negative double)
        System.out.println ("Math.sqrt (-5.0) = " + Math.sqrt (-5.0));
        System.out.println ();

        // Example 3 -- Math.pow:
        // Part (3a):  (returning a double to a given fractional power)
        System.out.println ("Math.pow (8, 1.0/3.0) = " + Math.pow (8, 1.0 / 3.0));

        // Part (3b):  (returning a double to a given whole number power)
        System.out.println ("Math.pow (2, 10) = " + Math.pow (2, 10));
        // Part (3c):  (returning a "NaN" value)

        System.out.println ("Math.pow (-32.0, 0.2) = " + Math.pow (-32.0, 0.2));
        // Part (3d):  (returning a double number to a given power, as an int)
        System.out.println ("(int)Math.pow (100, 0.25) = " + (int) Math.pow (100, 0.25));

    } // main method
} // MathMethodsExamples1 class

No comments:

Post a Comment