Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน nearbyint() ใน C++

ในบทความนี้ เราจะอภิปรายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน nearbyint() ใน C++ STL

nearbyint() คืออะไร?

ฟังก์ชัน nearbyint() เป็นฟังก์ชันสำเร็จรูปใน C++ STL ซึ่งถูกกำหนดในไฟล์หัวข้อ <cmath> ฟังก์ชัน nearbyint() ใช้เพื่อรับค่า integral ที่ปัดเศษตามอินพุต

ฟังก์ชันปัดเศษอินพุตเพื่อให้ได้ค่า integral ใกล้เคียงที่สุด วิธีการปัดเศษอธิบายโดย fegetround

ฟังก์ชันนี้ยอมรับค่าประเภท float, double, และ long double เป็นอาร์กิวเมนต์

ไวยากรณ์

double nearbyint(double num);
float nearbyint(float num);
long double nearbyint(long double num);

พารามิเตอร์

ฟังก์ชันยอมรับพารามิเตอร์ต่อไปนี้:

  • num - ค่าที่จะถูกปัดเศษ

ค่าที่ส่งคืน

ฟังก์ชันนี้ส่งคืนค่าที่ปัดเศษของ num

ตัวอย่าง

Input

nearbyint(2.13);

Output

2

Input

nearbyint(3.4);

Output

3

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

int main() {
    float var = 3.4;
    cout << "value of var is: " << var << endl;
    cout << "value after round off is: " << nearbyint(var);
    return 0;
}

ผลลัพธ์

value of var is: 3.4
value after round off is: 3

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

int main() {
    float var = 7.9;
    cout << "value of var is: " << var << endl;
    cout << "value after round off is: " << nearbyint(var);
    return 0;
}

ผลลัพธ์

value of var is: 7.9
value after round off is: 8