Due date: Wednesday, April 8, 2020.
Objective: To write methods in Java.
Create a project in Eclipse called hw9 and create a class called FloatMethods in it, containing the main function.
a. Smallest number
Write a static method that takes three float parameters, let's call them a, b, and c, and returns the smallest of the three numbers. You can use the function median from this week's PowerPoint slides as a model. Here is the header of the function:
static float smallest(float a, float b, float c)
In the main, ask the user to enter three numbers and then output the smallest of the three, after calling the function.
b. Almost equal
Write a static method that takes in three float numbers and checks if the first two are almost equal with a precision given by the third one. The header of the function should be
static boolean almostEqual(float a, float b, float epsilon)
For this, you need to test if the difference between a and b is less than or equal to epsilon. However, you don't know which of a and b is larger. You can either do a test for it, and if a is larger, check if a-b < epsilon, and return true, otherwise return false. If b is the larger one, check the same thing for b-a.
If you want to use a single conditional, you can test that -epsilon <= a-b <= epsilon (and remember the proper way to test this), which tells you the right answer no matter which of a and b is larger. The choice is yours which way you want to implement it.
Add a test in the main for this function. For example, almostEqual(2.15, 2.18, 0.1) should return true, but almostEqual(2.15, 2.18, 0.01) should return false.
c. Harmonic sum
Write a method that takes in an integer number, call it n, and computes the harmonic sum for this number. This is the sum of 1/i for i going from 1 to n. This value should be approximately equal to ln(n). The header of the function should be
static float harmonic(int n)
For example, if n=4, the function should return 1/1 + 1/2 + 1/3 + 1/4. You need to declare a float variable to hold the sum, then use a for loop with i going from 1 to n. Then in the loop, add 1/i to the sum. At the end, return the sum.
Add a test for this function in the main, where you ask the user to enter an integer number, input it in a variable, then call the function and output the result.
Upload the lab and homework .java files: RealNumber.java and FloatMethods.java, to Canvas in Assignments - Homework 9.