This Java program prompts the user to enter a float number, and then converts the number to its absolute value using a ternary operator. The result is printed to the console.
Note that the ternary operator is used to write a concise conditional expression that evaluates to one of two values based on a condition. In this case, the ternary operator replaces the use of an if statement to determine the sign of the input number. However, it's worth noting that the use of the ternary operator with floating-point numbers can sometimes result in unexpected behavior due to rounding errors, and so it may be safer to use the Math.abs() method instead.
import java.util.*; public class Float_Absolute { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a Float Number : "); float n = input.nextFloat(); float abs_val = (n >= 0) ? n : -n; System.out.println("Given value : "+n); System.out.println("Convert Float to Absolute value : "+abs_val); } }
Enter a Float Number : -84.921 Given value : -84.921 Convert Float to Absolute value : 84.921
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions