What is abs() in D?

The abs() function in D returns the absolute value of a number.

The figure below shows the mathematical representation of the abs() function.

Figure 1: Mathematical representation of the abs() function

Note: import std.math is required to use this function.

Syntax

abs(num)

num is the number whose absolute value is required

Parameter

The abs() function takes a number as a parameter.

Return value

The abs() function returns the absolute value of a number passed as a parameter.

Code

The following code shows how to use the abs() function in D:

import core.stdc.stdio;
import std.stdio;
//Header required for the function
import std.math;
int main()
{
//Positive number
writeln ("The value of abs(10) : ",abs(10));
//Zero
writeln ("The value of abs(0) : ",abs(0));
//Negative number
writeln ("The value of abs(-10) : ",abs(-10));
return 0;
}

Explanation

  • Line 4: We add the std.math header required for the abs() function.

  • Line 9: We calculate the absolute value of the positive number 10 using abs().

  • Line 12: We calculate the absolute value 0 using abs().

  • Line 15: We calculate the absolute value of the negative number -10 using abs().

Free Resources