Ở đây ta sẽ xem công dụng của hàm ldexp() trong C/C++. Hàm này trả về x * 2^exp. Nhận 2 đối số x và exp.
Cú pháp:
float ldexp (float x, int exp) double ldexp (double x, int exp) long double ldexp (long double x, int exp) double ldexp (T x, int exp)
Ví dụ cơ bản
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double a = 10, res;
int exp = 2;
res = ldexp(a, exp); // Tìm a*(2^exp)
cout << "The result is = " << res << endl;
return 0;
}
Kết quả
The result is = 40
Nếu kết quả quá lớn để biểu diễn, hàm trả về HUGE_VAL (hiển thị inf).
Ví dụ tràn số
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double a = 10, res;
int exp = 5000;
res = ldexp(a, exp);
cout << "The result is = " << res << endl;
return 0;
}
Kết quả
The result is = inf