logo

Metoda Java Math.abs().

The java.lang.Math.abs() Metoda zwraca wartość bezwzględną (dodatnią) wartości typu int. Ta metoda podaje wartość bezwzględną argumentu. Argument może mieć wartość int, double, long i float.

ciąg na liczbę całkowitą

Składnia:

 public static int abs(int i) public static double abs(double d) public static float abs(float f) public static long abs(long lng) 

Parametry:

 The argument whose absolute value is to be determined 

Powrót:

 This method returns the absolute value of the argument 
  • Jeśli jako argument podamy wartość dodatnią lub ujemną, ta metoda da wartość dodatnią.
  • Jeśli argumentem jest Nieskończoność , ta metoda spowoduje Pozytywna nieskończoność .
  • Jeśli argumentem jest NaN , ta metoda powróci NaN .
  • Jeśli argument jest równy wartości Integer.MIN_VALUE lub Long.MIN_VALUE, najbardziej ujemnej możliwej do przedstawienia wartości int lub wartości long, wynikiem jest ta sama wartość, która jest ujemna.

Przykład 1:

 public class AbsExample1 { public static void main(String args[]) { int x = 78; int y = -48; //print the absolute value of int type System.out.println(Math.abs(x)); System.out.println(Math.abs(y)); System.out.println(Math.abs(Integer.MIN_VALUE)); } } 
Przetestuj teraz

Wyjście:

 78 48 -2147483648 

Przykład 2:

 public class AbsExample2 { public static void main(String args[]) { double x = -47.63; double y = -894.37; //print the absolute value of double type System.out.println(Math.abs(x)); System.out.println(Math.abs(y)); System.out.println(Math.abs(7.0 / 0)); } } 
Przetestuj teraz

Wyjście:

 47.63 894.37 Infinity 

Przykład 3:

 public class AbsExample3 { public static void main(String args[]) { float x = -73.02f; float y = -428.0f; //print the absolute value of float type System.out.println(Math.abs(x)); System.out.println(Math.abs(y)); } } 
Przetestuj teraz

Wyjście:

 73.02 428.0 

Przykład 4:

 public class AbsExample4 { public static void main(String args[]) { long x = 78730343; long y = -4839233; //print the absolute value of long type System.out.println(Math.abs(x)); System.out.println(Math.abs(y)); System.out.println(Math.abs(Long.MIN_VALUE)); } } 
Przetestuj teraz

Wyjście:

 78730343 4839233 -9223372036854775808