Как найти модуль числа в джава

Описание

Метод Math.abs() – дает абсолютное значение аргумента, простыми словами – мы получаем модуль числа. Аргумент может быть int, float, long, double, short, byte.

Синтаксис

Варианты метода приведены ниже:

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

Параметры

Подробная информация о параметрах:

  • Любой примитивный тип данных.

Возвращаемое значение

  • В Java Math.abs() возвращает абсолютное значение аргумента (модуль числа).

Пример

public class Test{ 

   public static void main(String args[]){
      Integer a = -8;
      double d = -100;
      float f = -90;    
						
      System.out.println(Math.abs(a));
      System.out.println(Math.abs(d));     
      System.out.println(Math.abs(f));    
   }
}

Получим следующий результат:

8
100.0
90.0

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Absolute value refers to the positive value corresponding to the number passed as in arguments. Now geek you must be wondering what exactly it means so by this it is referred no matter what be it positive or negative number been passed for computation, the computation will occur over the positive corresponding number in both cases.  So in order to compute the absolute value for any number we do have a specified method in Java referred to as abs() present inside Math class present inside java.lang package. 

    The java.lang.Math.abs() returns the absolute value of a given argument. 

    • If the argument is not negative, the argument is returned.
    • If the argument is negative, the negation of the argument is returned.

    Syntax : 

    public static DataType abs(DataType a)

    Parameters: Int, long, float, or double value whose absolute value is to be determined

    Returns Type: This method returns the absolute value of the argument.

    Exceptions Thrown: ArithmeticException 

    Tip: One must be aware of generic return type as follows:

    • If the argument is of double or float type: 
      • If the argument is positive zero or negative zero, the result is positive zero.
      • If the argument is infinite, the result is positive infinity.
      • If the argument is NaN, the result is NaN.
    • If the argument is of int or long type: If the argument is equal to the value of Integer.MIN_VALUE or Long.MIN_VALUE, the most negative representable int or long value, the result is that same value, which is negative.

    Example 1:

    Java

    import java.lang.Math;

    class GFG {

        public static void main(String[] args)

        {

            int n = -7;

            System.out.println(

                "Without applying Math.abs() method : " + n);

            int value = Math.abs(n);

            System.out.println(

                "With applying Math.abs() method : " + value);

        }

    }

    Output

    Without applying Math.abs() method : -7
    With applying Math.abs() method : 7

    Example 2:

    Java

    import java.lang.Math;

    class GFG {

        public static void main(String args[])

        {

            float a = 123.0f;

            float b = -34.2323f;

            double c = -0.0;

            double d = -999.3456;

            int e = -123;

            int f = -0;

            long g = -12345678;

            long h = 98765433;

            System.out.println(Math.abs(a));

            System.out.println(Math.abs(b));

            System.out.println(Math.abs(1.0 / 0));

            System.out.println(Math.abs(c));

            System.out.println(Math.abs(d));

            System.out.println(Math.abs(e));

            System.out.println(Math.abs(f));

            System.out.println(Math.abs(Integer.MIN_VALUE));

            System.out.println(Math.abs(g));

            System.out.println(Math.abs(h));

            System.out.println(Math.abs(Long.MIN_VALUE));

        }

    }

    Output

    123.0
    34.2323
    Infinity
    0.0
    999.3456
    123
    0
    -2147483648
    12345678
    98765433
    -9223372036854775808

    Last Updated :
    09 Nov, 2021

    Like Article

    Save Article

    The java.lang.Math.abs() method returns the absolute (Positive) value of a int value. This method gives the absolute value of the argument. The argument can be int, double, long and float.

    Syntax:

    Parameters:

    Return:

    • If we provide positive or negative value as argument, this method will result positive value.
    • If the argument is Infinity, this method will result Positive Infinity.
    • If the argument is NaN, this method will return NaN.
    • If the argument is equal to the value of Integer.MIN_VALUE or Long.MIN_VALUE, the most negative representable int value or long value, the result is that same value, which is negative.

    Example 1:

    Test it Now

    Output:

    Example 2:

    Test it Now

    Output:

    Example 3:

    Test it Now

    Output:

    Example 4:

    Test it Now

    Output:

    78730343
    4839233
    -9223372036854775808
    


    Youtube
    For Videos Join Our Youtube Channel: Join Now


    Feedback

    • Send your Feedback to [email protected]

    Help Others, Please Share

    facebook
    twitter
    pinterest





    Описание

    Метод Math.abs() — дает абсолютное значение аргумента, простыми словами — мы получаем модуль числа. Аргумент может быть int, float, long, double, short, byte.

    Синтаксис

    Варианты метода приведены ниже:

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

    Параметры

    Подробная информация о параметрах:

    • Любой примитивный тип данных.

    Возвращаемое значение

    • В Java Math.abs() возвращает абсолютное значение аргумента (модуль числа).

    Пример

    public class Test{ 
    
       public static void main(String args[]){
          Integer a = -8;
          double d = -100;
          float f = -90;    
    						
          System.out.println(Math.abs(a));
          System.out.println(Math.abs(d));     
          System.out.println(Math.abs(f));    
       }
    }
    

    Получим следующий результат:

    8
    100.0
    90.0
    

    Ezoic

    Find Absolute Value in Java – Math.abs() | To find the absolute value of a number, the abs() method is given in the java.lang.Math class. There are several overloaded forms of abs() methods to accept different types of arguments and return accurate values. All of them return the absolute value of an argument.

    • If the argument is not negative, then the same argument is returned.
    • If the argument is negative, then the negation of the argument is returned.

    The overloaded forms of java.lang.Math.abs() method are,

    • public static int abs(int a)
    • public static long abs(long a)
    • public static float abs(float a)
    • public static double abs(double a)

    These methods are implemented like,

    public static int abs(int a) {
       return (a < 0) ? -a : a;
    }

    Math.abs() examples

    public class Test{
       public static void main(String[] args) {
    
          // argument is int type
          System.out.println(Math.abs(-9)); // 9
          System.out.println(Math.abs(9)); // 9
    
          // argument is long type
          System.out.println(Math.abs(-10L)); // 10
          System.out.println(Math.abs(10L)); // 10
    
          // argument is float type
          System.out.println(Math.abs(-9F)); // 9.0
          System.out.println(Math.abs(9F)); // 9.0
    
          // argument is double type
          System.out.println(Math.abs(-10.0)); // 10.0
          System.out.println(Math.abs(10.0)); // 10.0
       }
    }

    If the argument is negative then all of them return the absolute value as the negation of the argument, else the same argument is returned back.

    If we import the Math class statically and then we can invoke the abs() method without calling through its class name.

    import static java.lang.Math.*;
    public class Test{
       public static void main(String[] args) {
          System.out.println(abs(-9)); // 9
          System.out.println(abs(9)); // 9
       }
    }

    The “import static java.lang.Math.*;” statement will import all static members of the Math class. But if we want to import only the abs() method of the Math class, not another static method and variables of Math class then we can use the “import static java.lang.Math.abs;” statement. Learn more about static import in Java

    import static java.lang.Math.abs;
    public class Test {
       public static void main(String[] args) {
          System.out.println(abs(-9)); // 9
          System.out.println(abs(9)); // 9
       }
    }

    Output:-

    9
    9

    Special Cases while finding absolute value in Java

    1) When the passed argument is of int data type and it is equal to the Integer.MIN_VALUE (i.e. -2147483648 or -231) then abs(int a) returns the same value, which is negative.

    System.out.println(Math.abs(-2147483648));

    Output:- -2147483648

    2) Similarly, when the passed value is of long data type and it is equal to Long.MIN_VALUE (i.e. -9223372036854775808 or -263) then abs(long a) returns absolute value as the same value, which is negative.

    System.out.println(Math.abs(-9223372036854775808L));

    Output:- -9223372036854775808

    3) If the argument is positive zero or negative zero, the result is positive zero.

    System.out.println(Math.abs(-0)); // 0
    System.out.println(Math.abs(0)); // 0
    System.out.println(Math.abs(-0.0)); // 0.0
    System.out.println(Math.abs(0.0)); // 0.0

    Output:-

    0
    0
    0.0
    0.0

    4) If the argument is infinite, the result is positive infinity.

    System.out.println(Math.abs(Double.POSITIVE_INFINITY));
    System.out.println(Math.abs(Double.NEGATIVE_INFINITY));

    Output:-

    Infinity
    Infinity

    5) If the argument is NaN, the result is NaN.

    System.out.println(Math.abs(Double.NaN));
    System.out.println(Math.abs(Float.NaN));

    Output:-

    NaN
    NaN

    If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

    Ezoic

    Добавить комментарий