Home > Article > Backend Development > How to express absolute value in c++
The way to get the absolute value of a number in C is to use the abs() function (integers) and the fabs() function (floating point numbers). The abs(x) function returns an absolute value of integer type, while the fabs(x) function returns an absolute value of double type and requires the inclusion of the corresponding header files (cstdlib and cmath).
Absolute value representation in C
In C, you can use abs()
Function to get the absolute value of a number. Absolute value refers to the value of a number after removing the positive and negative signs.
The following is the syntax for using the abs()
function:
<code class="cpp">#include <cstdlib> int abs(int x);</code>
Where, x
is the parameter to calculate the absolute value. abs()
The function returns an absolute value of integer type.
For example:
<code class="cpp">#include <cstdlib> int main() { int num = -5; int abs_num = abs(num); cout << "绝对值:" << abs_num << endl; return 0; }</code>
Output:
<code>绝对值:5</code>
In the above example, the num
variable is -5, and abs(num)# is called ## After, return 5 and save it in the
abs_num variable.
Avoid errors
It should be noted that theabs() function can only be used for integer types. If you try to use
abs() with floating point or other types of data, the compiler will issue an error.
fabs() x The above is the detailed content of How to express absolute value in c++. For more information, please follow other related articles on the PHP Chinese website! function.
fabs() The function is declared in the
header file, and the syntax is as follows:
<code class="cpp">#include <cmath>
double fabs(double x);</code>
Among them, is used to calculate the absolute value Floating point number.
fabs() The function returns an absolute value of double precision type.
<code class="cpp">#include <cmath>
int main() {
double num = -3.14;
double abs_num = fabs(num);
cout << "绝对值:" << abs_num << endl;
return 0;
}</code>
Output:
<code>绝对值:3.14</code>