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

How to calculate absolute value in c++

下次还敢
下次还敢Original
2024-05-06 18:21:18938browse

There are three ways to find the absolute value in C: Use the abs() function to calculate the absolute value of any type of number. Using the std::abs() function, you can calculate the absolute value of integers, floating point numbers, and complex numbers. Manual calculation of absolute values, suitable for simple integers.

How to calculate absolute value in c++

How to find the absolute value in C

There are the following methods to get the absolute value in C:

1. Use the abs() function

abs() function is used to calculate the absolute value of any type of number. It is defined in the header file, accepts a parameter and returns the absolute value of the parameter. For integers, it returns an unsigned integer, and for floating point numbers, it returns a double.

<code class="cpp">#include <cstdlib>

int main() {
  int num = -10;
  double num2 = -3.14;

  std::cout << "绝对值:" << abs(num) << std::endl;  // 输出:10
  std::cout << "绝对值:" << abs(num2) << std::endl;  // 输出:3.14
}</code>

2. Use std::abs() function

std::abs() function is an overloaded version in the C standard library and is used for calculations The absolute value of integers, floating point numbers, and complex numbers. Similar to the abs() function, it is also defined in the header file.

<code class="cpp">#include <cstdlib>

int main() {
  int num = -10;
  double num2 = -3.14;
  std::complex<double> num3(-2, 3);

  std::cout << "绝对值:" << std::abs(num) << std::endl;  // 输出:10
  std::cout << "绝对值:" << std::abs(num2) << std::endl;  // 输出:3.14
  std::cout << "绝对值:" << std::abs(num3) << std::endl;  // 输出:3.60555
}</code>

3. Manually calculate the absolute value

For simple integers, you can write the absolute value by hand by using the conditional operator:

<code class="cpp">int my_abs(int num) {
  return (num >= 0) ? num : -num;
}</code>

The above is the detailed content of How to calculate 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