該函數查找給定數字的絕對值。
假設一個數字是 'x':
abs(x) = |x|;
abs() 和 fabs() 的區別
abs() 函數不支持 float 或 double 類型參數,而 fabs() 函數支持 float、double 和 integer 類型參數。
用法
int abs( int x);
long int abs(long int x );
long long int abs(long long int x);
參數
x:要確定絕對值的值。
返回值
它返回 x 的絕對值。
例子1
讓我們看一個簡單的例子,當 x 的值為負時。
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int x= -9;
std::cout << "Value of x is:" <<x<< std::endl;
cout<<"Absolute value of x is:"<<abs(x);
return 0;
}
輸出:
Value of x is:-9 Absolute value of x is:9
在本例中,abs() 函數計算 x 的絕對值並返回值 9。
例子2
讓我們看一個簡單的例子,當 x 的值為正時。
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int x= 89;
std::cout << "Value of x is:" <<x<< std::endl;
cout<<"Absolute value of x is:"<<abs(x);
return 0;
}
輸出:
Value of x is:89 Absolute value of x is:89
在本例中,abs() 函數計算 x 的絕對值。
相關用法
- C++ Math acosh()用法及代碼示例
- C++ Math asinh()用法及代碼示例
- C++ Math atan()用法及代碼示例
- C++ Math asin()用法及代碼示例
- C++ Math atan2()用法及代碼示例
- C++ Math acos()用法及代碼示例
- C++ Math atanh()用法及代碼示例
- C++ Math scalbn()用法及代碼示例
- C++ Math isgreater()用法及代碼示例
- C++ Math fabs()用法及代碼示例
- C++ Math islessgreater()用法及代碼示例
- C++ Math log2()用法及代碼示例
- C++ Math nearbyint()用法及代碼示例
- C++ Math tan()用法及代碼示例
- C++ Math log()用法及代碼示例
- C++ Math nextafter()用法及代碼示例
- C++ Math fdim()用法及代碼示例
- C++ Math isfinite()用法及代碼示例
- C++ Math erfc()用法及代碼示例
- C++ Math sinh()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ Math abs()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。