Metoda Java Math abs () zwraca wartość bezwzględną określonej wartości.
Składnia abs()
metody to:
Math.abs(num)
Tutaj abs()
jest metoda statyczna. Stąd mamy dostęp do metody z użyciem nazwy klasy, Math
.
abs () Parametry
abs()
Sposób przyjmuje jeden parametr.
- num - liczba którego bezwzględna wartość jest zwracana. Numer może być:
int
double
float
long
abs () Wartość zwracana
- zwraca wartość bezwzględną podanej liczby
- zwraca wartość dodatnią, jeśli podana liczba jest ujemna
Przykład 1: Java Math abs () z liczbami dodatnimi
import java.lang.Math; class Main ( public static void main(String() args) ( // create variables int a = 7; long b = 23333343; double c = 9.6777777; float d = 9.9f; // print the absolute value System.out.println(Math.abs(a)); // 7 System.out.println(Math.abs(c)); // 9.6777777 // print the value without negative sign System.out.println(Math.abs(b)); // 23333343 System.out.println(Math.abs(d)); // 9.9 ) )
W powyższym przykładzie zaimportowaliśmy java.lang.Math
pakiet. Jest to ważne, jeśli chcemy używać metod Math
klasy. Zwróć uwagę na wyrażenie,
Math.abs(a)
Tutaj bezpośrednio użyliśmy nazwy klasy do wywołania metody. To dlatego, że abs()
jest to metoda statyczna.
Przykład 2: Java Math abs () z liczbami ujemnymi
import java.lang.Math; class Main ( public static void main(String() args) ( // create variables int a = -35; long b = -141224423L; double c = -9.6777777d; float d = -7.7f; // get the absolute value System.out.println(Math.abs(a)); // 35 System.out.println(Math.abs(b)); // 141224423 System.out.println(Math.abs(c)); // 9.6777777 System.out.println(Math.abs(d)); // 7.7 ) )
Tutaj widzimy, że abs()
metoda konwertuje wartość ujemną na wartość dodatnią.