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