What is the usage of the absolute value function in C#?

The absolute value function in C# can be implemented using the Abs method within the Math class. This method can return the absolute value of an integer, long integer, double-precision floating point number, single-precision floating point number, or decimal number.

Here is how to use:

int num1 = -10;
int absNum1 = Math.Abs(num1);
Console.WriteLine(absNum1); // 输出:10

double num2 = -5.5;
double absNum2 = Math.Abs(num2);
Console.WriteLine(absNum2); // 输出:5.5

decimal num3 = -2.25m;
decimal absNum3 = Math.Abs(num3);
Console.WriteLine(absNum3); // 输出:2.25

In the above code, we used the Math.Abs method to calculate the absolute values of an integer, double-precision floating-point number, and decimal number respectively, then printed out the results.

bannerAds