Home  >  Article  >  Backend Development  >  How to express absolute value in c++

How to express absolute value in c++

下次还敢
下次还敢Original
2024-05-01 13:03:17895browse

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).

How to express absolute value in c++

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 the

abs() 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.

To calculate the absolute value of a floating point number, you can use the

fabs() 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,

x is used to calculate the absolute value Floating point number. fabs() The function returns an absolute value of double precision type.

For example:

<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>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use bool in c++Next article:How to use bool in c++