Confused with Selection (floating point numbers)

Viewed 60

I'm learning Java online and I'm having trouble with this. I know it might have something to do with the BigDecimal Class but other than that I'm not sure. Sorry for poor indentation.

public class Practice {
     
    public static void main(String[] args) {
         
        double b = 1.3333;
          
        int c = 4, d = 3;
          
        final double TOLERANCE = 0.001;

        /*** TODO: Write an if statement to serve as the header for the conditional block below.
                   Execute the first block if the floating point outcome of c divided by d is 
                   within the given TOLERANCE of b. ***/
        
        {
            System.out.println("Value within the tolerance level!");
        } else {
            System.out.println("Value outside the tolerance level!");
        }
    }
}
1 Answers
/*** TODO: Write an if statement to serve as the header for the conditional block below.
     Execute the first block if the floating point outcome of c divided by d is 
     within the given TOLERANCE of b. ***/

You need to complete missing if statement with a division operation which needs to be compared with tolerance. The division operation should outcome floating point, and should be compared with variable b to check whether it is within tolerance or not.

If you divide two integers, it is called integer division and it outcomes integer again. To have floating point number, you need to cast at least one of your numbers to float. Here is the difference and how casting is done:

System.out.println(c / d); // result is 1, out of tolerance. this is integer division
System.out.println((float) c / d); // result is 1.3333334, within tolerance

Another point about comparing with tolerance is that we need absolute difference for comparison. To do that there is method abs() in Math class: Math.abs(((float) c / d) - b)

So your code should be like this at the end:

public static void main(String[] args) {
    double b = 1.3333;

    int c = 4, d = 3;

    final double TOLERANCE = 0.001;

    if (Math.abs(((float) c / d) - b) < TOLERANCE){
        System.out.println("Value within the tolerance level!");
    } else {
        System.out.println("Value outside the tolerance level!");
    }
}
Related