230k views
3 votes
write java code to test whether an integer n equals 10 and whether a floating-point number x is approximately equal to 10

User Droppy
by
3.9k points

1 Answer

0 votes

Answer:

Here is Java code that tests whether an integer n equals 10, and whether a floating-point number x is approximately equal to 10.

// Test if an integer n equals 10

int n = 10;

if (n == 10) {

System.out.println("n equals 10");

} else {

System.out.println("n does not equal 10");

}

// Test if a floating-point number x is approximately equal to 10

double x = 9.99999;

if (Math.abs(x - 10) < 0.00001) {

System.out.println("x is approximately equal to 10");

} else {

System.out.println("x is not approximately equal to 10");

}

Step-by-step explanation:

In this code, we first define an integer n and set it to 10. We then use an if statement to check if n equals 10. If it does, we print a message saying that n equals 10. Otherwise, we print a message saying that n does not equal 10.

Next, we define a floating-point number x and set it to a value that is close to 10. We then use another if statement to check if x is approximately equal to 10. To do this, we use the abs method from the Math class to calculate the absolute difference between x and 10, and check if it is less than a certain threshold (in this case, 0.00001). If the difference is less than the threshold, we print a message saying that x is approximately equal to 10. Otherwise, we print a message saying that x is not approximately equal to 10.

Overall, this code demonstrates two different ways to test whether a value is equal to or approximately equal to a given number. It can be useful in situations where you need to check if a value meets

User Alba
by
3.3k points