Write a Java program that accepts two floating­point numbers and checks whether they are the same up to two decimal plac | Core Java Forum
H
Harika Posted on 11/04/2024

in this program this logic is used 

if(Math.abs(num1-num2)<=0)

{

System.out.println("numbers are same");

}

else

{System.out.println("numbers are different");

}

please explian me how this logic will work for this asked condition in the question

 


Y
Yogesh Chawla Replied on 11/04/2024

Math class belong to java.lang package.
 
abs() function leaves positive numbers unchanged and converts negative numbers into positive 
number. 
 
For example: 
Math.abs(-5);  // Returns 5
 
abs function is useful when calculating the distance between two points because distance will always comes positive.
 
For example: Calculate the difference between two numbers
public class Class1 {

	public static void main(String[] args) {
		Class1 obj = new Class1();
		System.out.println(obj.diff(-5, 5)); // Actual Output is -10 but abs made it to 10 
	}

	int diff(int num1, int num2) {
		return Math.abs(num1 - num2);
	}
}

package com.programming.class1;

public class Class2{
	public static void main(String[] args) {
		show();
	}
	
	static void show() {
		int num1 = 10, num2 = 19;
		System.out.println(Math.abs(num1-num2)); 
		//Actual Output is -9 but abs made to 9
		//that's the reason 9<0 failed and else will run
		if(Math.abs(num1-num2)<=0){
			System.out.println("numbers are same");
		}
		else{
			System.out.println("numbers are different");
		}
	}
}