Java Math abs ()

Metoda Java Math abs () vrne absolutno vrednost podane vrednosti.

Sintaksa abs()metode je:

 Math.abs(num)

Tu abs()je statična metoda. Zato smo dostop do metode z uporabo imena razreda, Math.

parametri abs ()

abs()Postopek traja samo en parameter.

  • num - število, katerega absolutna vrednost se vrne. Številka je lahko:
    • int
    • double
    • float
    • long

abs () Vrnjena vrednost

  • vrne absolutno vrednost podanega števila
  • vrne pozitivno vrednost, če je določeno število negativno

Primer 1: Java Math abs () s pozitivnimi številkami

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

V zgornjem primeru smo java.lang.Mathpaket uvozili . To je pomembno, če želimo uporabiti metode Mathrazreda. Upoštevajte izraz,

 Math.abs(a)

Tu smo za klic metode neposredno uporabili ime razreda. To je zato, ker abs()je statična metoda.

Primer 2: Java Math abs () z negativnimi številkami

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

Tu lahko vidimo, da abs()metoda negativno vrednost pretvori v pozitivno vrednost.

Zanimive Članki...