Bibliotheksreferenz

Absolutbetrag

Der Betrag zeigt dir an, wie weit eine Zahl von null entfernt ist.

Math.Abs

Ein einfaches Beispiel

Am Anfang−3
Ergebnis3
Program.cs
using System;

Console.WriteLine(Math.Abs(-3));
Ausgabe
3
Anzeigen

Beispiele aus dem Alltag

Es ist −6 Grad draußen. Wie viele Grad unter Null ist das?

Am Anfang−6 → 0
Ergebnis6
Program.cs
using System;

int temperature = -6;
Console.WriteLine(Math.Abs(temperature));
Ausgabe
6

Das Ziel ist 15 Punkte, die Punktzahl beträgt 12. Wie weit sind sie voneinander entfernt?

Am Anfang12 − 15
Ergebnis3
Program.cs
using System;

int score = 12;
int target = 15;
Console.WriteLine(Math.Abs((score - target)));
Ausgabe
3

Ein Aufzug fährt von der Etage 5 auf die Etage 2. Wie viele Stockwerke legt er zurück?

Am Anfang5 → 2
Ergebnis3
Program.cs
using System;

int start = 5;
int finish = 2;
Console.WriteLine(Math.Abs((finish - start)));
Ausgabe
3

Probiere es hier mit kleinen positiven und negativen Zahlen. Das Ergebnis ist der Abstand zur Null.

Beispiel ausführen
Terminal
dotnet new console --output Lesson
cp Program.cs Lesson/Program.cs
dotnet run --project Lesson
Offizielle Dokumentation