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

How to express absolute value in c++

下次还敢
Release: 2024-05-01 13:03:17
Original
1211 people have browsed it

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>
Copy after login

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>
Copy after login

Output:

<code>绝对值:5</code>
Copy after login

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>
Copy after login
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>
Copy after login
Output:

<code>绝对值:3.14</code>
Copy after login

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!

Related labels:
c++
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template