Java Math abs ()

Java Math abs () metode atgriež norādītās vērtības absolūto vērtību.

Metodes sintakse abs()ir šāda:

 Math.abs(num)

Šeit abs()ir statiska metode. Tādējādi mēs piekļūstam metodei, izmantojot klases nosaukumu Math,.

abs () parametri

abs()Metode ņem vienu parametru.

  • num - skaitlis, kura absolūtā vērtība ir jāatgriež. Numurs var būt:
    • int
    • double
    • float
    • long

abs () Atgriešanās vērtība

  • atgriež norādītā skaitļa absolūto vērtību
  • atgriež pozitīvo vērtību, ja norādītais skaitlis ir negatīvs

1. piemērs: Java Math abs () ar pozitīviem skaitļiem

 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 ) )

Iepriekš minētajā piemērā mēs esam importējuši java.lang.Mathpaketi. Tas ir svarīgi, ja mēs vēlamies izmantot Mathklases metodes . Ievērojiet izteicienu,

 Math.abs(a)

Šeit, lai izsauktu metodi, mēs tieši izmantojām klases nosaukumu. Tas ir tāpēc, ka abs()tā ir statiska metode.

2. piemērs: Java Math abs () ar negatīviem skaitļiem

 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 ) )

Šeit mēs varam redzēt, ka abs()metode negatīvo vērtību pārvērš par pozitīvu.

Interesanti raksti...