Home > Backend Development > C++ > body text

How to express absolute value in c++

下次还敢
Release: 2024-05-06 18:18:14
Original
433 people have browsed it

In C, the absolute value can be calculated using the abs() function, which works on any arithmetic type value and returns a value that is the same as the absolute value of the input value: include the header files and < ;cmath>. Calculate the absolute value using the abs(value) function, where value is an arithmetic type value. The abs() function returns the same absolute value as the input value, and its return value type is the same as the input value.

How to express absolute value in c++

In C represents the absolute value

In C, you can use the built-in function abs() to calculate the absolute value. This function accepts one argument, which can be a value of any arithmetic type (for example, int, float, double). abs() The function returns a value that is the same as the absolute value of the input value.

Sample code:

<code class="cpp">#include <iostream>
#include <cmath>

int main() {
  int a = -10;
  float b = -3.14;
  double c = -123.45;

  std::cout << "Absolute value of " << a << ": " << abs(a) << std::endl;
  std::cout << "Absolute value of " << b << ": " << abs(b) << std::endl;
  std::cout << "Absolute value of " << c << ": " << abs(c) << std::endl;

  return 0;
}</code>
Copy after login

Output:

<code>Absolute value of -10: 10
Absolute value of -3.14: 3.14
Absolute value of -123.45: 123.45</code>
Copy after login

Note:

  • abs() Function only works on arithmetic types. The compiler will generate an error if you try to pass a value of non-arithmetic type to abs().
  • abs() The return value type of the function is the same as the input value.

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