Comment convertir un nombre négatif en positif en Java

Comment convertir un nombre négatif en positif en Java

Pour convertir un nombre négatif en nombre positif (c'est ce qu'on appelle la valeur absolue), utiliseMath.abs(). Cette méthodeMath.abs() fonctionne comme ceci "` number = (number <0? -nombre: nombre); `".

Voir un exemple complet:

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

    }

}

Sortie

Total : 3
Total 2 (absolute value) : 5

Dans ce cas,Math.abs(-1) convertira le nombre négatif 1 en positif 1.