在cstdlib頭文件中定義了abs(),labs(),llabs()函數。這些函數返回作為其參數輸入到它們的整數的絕對值。
-
abs()函數:此函數的輸入是C中int類型的值和C++中int類型,long int或long long int的值。在C中,輸出是int類型,在C++中,輸出具有與輸入相同的數據類型。下麵是示例C++程序,以顯示abs()函數的工作。
// CPP program to illustrate // abs() function #include <cstdlib> #include <iostream> using namespace std; int main() { int val1, val2; /// finding absolute value using /// abs() function. val1 = abs(22); val2 = abs(-43); cout << "abs(22) = " << val1 << "\n"; cout << "abs(-43) = " << val2 << "\n"; return 0; }
Output: abs(22) = 22 abs(-43) = 43
-
labs()函數:這是abs()函數的long int版本。輸入和輸出均為long int類型。下麵是示例C++程序,以顯示labs()函數的工作。 post_top_responsive
// CPP program to illustrate // labs() function #include <cstdlib> #include <iostream> using namespace std; int main() { int val1, val2; /// finding absolute value using /// labs() function. val1 = labs(1234355L); val2 = labs(-4325600L); cout << "labs(1234355L) = " << val1 << "\n"; cout << "labs(-4325600L) = " << val2 << "\n"; return 0; }
Output: labs(1234355L) = 1234355 labs(-4325600L) = 4325600
-
llabs()函數:這是abs()函數的long long int版本。輸入和輸出均為long long int類型。下麵是示例C++程序,以顯示llabs()函數的工作。
// CPP program to illustrate // llabs() function #include <cstdlib> #include <iostream> using namespace std; int main() { int val1, val2; /// finding absolute value using /// labs() function. val1 = llabs(1234863551LL); val2 = llabs(-432592160LL); cout << "llabs(1234863551LL) = " << val1 << "\n"; cout << "llabs(-432592160LL) = " << val2 << "\n"; return 0; }
Output: llabs(1234863551LL) = 1234863551 llabs(-432592160LL) = 432592160
相關用法
注:本文由純淨天空篩選整理自nik1996大神的英文原創作品 abs(), labs(), llabs() functions in C/C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。