Javaで負の数値を正の値に変換する方法

Javaで負の数を正に変換する方法

負の数を正の数(これは絶対値と呼ばれます)に変換するには、Math.abs()を使用します。 このMath.abs()メソッドは、次のように機能します。「 `number =(number <0? -番号:番号); `"。

完全な例を参照してください。

package com.example;

public class app{

    public static void main(String[] args) {

        int total = 1 + 1 + 1 + 1 + (-1);

        //output 3
        System.out.println("Total : " + total);

        int total2 = 1 + 1 + 1 + 1 + Math.abs(-1);

        //output 5
        System.out.println("Total 2 (absolute value) : " + total2);

    }

}

出力

Total : 3
Total 2 (absolute value) : 5

この場合、Math.abs(-1)は負の数1を正の1に変換します。