Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Hàm ceil() và floor() trong C++


Hàm ceil() - Làm tròn lên

Trả về số nguyên nhỏ nhất lớn hơn hoặc bằng giá trị cho trước. Khai báo trong header <cmath>. Tham số kiểu double/float/long double.

Cú pháp:

double ceil(double x);
float ceil(float x);

Ví dụ

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    float var = 1234.25;
    float res;
    res = ceil(var);
    cout << "Ceil value of " << var << " = " << res << endl;
    return 0;
}

Kết quả

Ceil value of 1234.25 = 1235

Hàm floor() - Làm tròn xuống

Trả về số nguyên lớn nhất nhỏ hơn hoặc bằng giá trị cho trước. Cũng trong <cmath>. Tham số double/float/long double.

Cú pháp:

double floor(double x);
float floor(float x);

Ví dụ

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    float var = 211.876;
    float res;
    res = floor(var);
    cout << "Floor value of " << var << " = " << res << endl;
    return 0;
}

Kết quả

Floor value of 211.876 = 211