ในไลบรารี cstdlib ของ C++ มีฟังก์ชันต่างๆ ในการรับค่าสัมบูรณ์ ยกเว้นจาก abs โดยทั่วไปจะใช้ abs สำหรับอินพุตประเภท int ใน C และ int ยาวและยาวใน C ++ ส่วนอื่นๆ ใช้สำหรับข้อมูลแบบยาวและแบบยาว เป็นต้น เรามาดูการใช้งานของฟังก์ชันเหล่านี้กัน
ฟังก์ชัน abs()
ฟังก์ชันนี้ใช้สำหรับข้อมูลประเภท int ดังนั้นนี่จะคืนค่าสัมบูรณ์ของอาร์กิวเมนต์ที่กำหนด ไวยากรณ์เป็นเหมือนด้านล่าง
int abs(int argument)
ตัวอย่าง
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
int x = -145;
int y = 145;
cout << "Absolute value of " << x << " is: " << abs(x) << endl;
cout << "Absolute value of " << y << " is: " << abs(y) << endl;
} ผลลัพธ์
Absolute value of -145 is: 145 Absolute value of 145 is: 145
ฟังก์ชันแล็บ()
ฟังก์ชันนี้ใช้สำหรับข้อมูลประเภทยาว ดังนั้นนี่จะคืนค่าสัมบูรณ์ของอาร์กิวเมนต์ที่กำหนด ไวยากรณ์เป็นเหมือนด้านล่าง
long labs(long argument)
ตัวอย่าง
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
long x = -9256847L;
long y = 9256847L;
cout << "Absolute value of " << x << " is: " << labs(x) << endl;
cout << "Absolute value of " << y << " is: " << labs(y) << endl;
} ผลลัพธ์
Absolute value of -9256847 is: 9256847 Absolute value of 9256847 is: 9256847
ฟังก์ชัน llabs()
ฟังก์ชันนี้ใช้สำหรับข้อมูลแบบยาว ดังนั้นนี่จะคืนค่าสัมบูรณ์ของอาร์กิวเมนต์ที่กำหนด ไวยากรณ์เป็นเหมือนด้านล่าง
long long labs(long long argument)
ตัวอย่าง
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
long long x = -99887654321LL;
long long y = 99887654321LL;
cout << "Absolute value of " << x << " is: " << llabs(x) << endl;
cout << "Absolute value of " << y << " is: " << llabs(y) << endl;
} ผลลัพธ์
Absolute value of -99887654321 is: 99887654321 Absolute value of 99887654321 is: 99887654321