So konvertieren Sie negative Zahlen in positive in Java
Verwenden SieMath.abs(), um eine negative Zahl in eine positive Zahl umzuwandeln (dies wird als absoluter Wert bezeichnet). DieseMath.abs()-Methode funktioniert wie folgt: `` number = (number <0? -Nummer: Nummer); `".
Sehen Sie sich ein vollständiges Beispiel an:
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);
}
}
Ausgabe
Total : 3 Total 2 (absolute value) : 5
In diesem Fall wandeltMath.abs(-1) die negative Zahl 1 in die positive 1 um.