Home > Article > Backend Development > How to use absolute value in c++
There are two ways to obtain the absolute value in C: 1. Use the built-in function abs() to obtain the absolute value of an integer or floating point type; 2. Use the generic function std::abs(), Get the absolute values of various data types that support absolute value operations.
Two ways to get the absolute value in C
In C, there are two ways to get the absolute value Type:
1. Use the abs() function
abs()
function is a built-in function in the C standard library, which can obtain The absolute value of an integer or floating-point number.
Syntax:
<code class="cpp">int abs(int n); double abs(double d);</code>
For example:
<code class="cpp">int n = -5; cout << abs(n) << endl; // 输出:5 double d = -3.14; cout << abs(d) << endl; // 输出:3.14</code>
2. Use std::abs() function
std::abs()
function is a generic function introduced in C 11, which can obtain the absolute value of any data type that supports absolute value operations.
Syntax:
<code class="cpp">template<typename T> T abs(T value);</code>
For example:
<code class="cpp">int n = -5; cout << std::abs(n) << endl; // 输出:5 double d = -3.14; cout << std::abs(d) << endl; // 输出:3.14 complex<double> c(3, 4); cout << std::abs(c) << endl; // 输出:5 (复数的模)</code>
Selection method:
abs()
function. std::abs()
function. The above is the detailed content of How to use absolute value in c++. For more information, please follow other related articles on the PHP Chinese website!