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:
int abs(int n); double abs(double d);
For example:
int n = -5; cout << abs(n) << endl; // 输出:5 double d = -3.14; cout << abs(d) << endl; // 输出:3.14
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:
template T abs(T value);
For example:
int n = -5; cout << std::abs(n) << endl; // 输出:5 double d = -3.14; cout << std::abs(d) << endl; // 输出:3.14 complex c(3, 4); cout << std::abs(c) << endl; // 输出:5 (复数的模)
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!