Ở đây chúng ta sẽ thấy cách in một số số dấu phẩy động lên đến một số chữ số thập phân được xác định trước. Trong C ++, chúng ta có thể sử dụng setpre precision với cout để thực hiện từ này. Điều này có trong tệp tiêu đề iomanip trong C ++.
Mã mẫu
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double x = 2.3654789d;
cout << "Print up to 3 decimal places: " << setprecision(3) << x << endl;
cout << "Print up to 2 decimal places: " << setprecision(2) << x << endl;
cout << "Print up to 7 decimal places: " << setprecision(7) << x << endl;
} Đầu ra
Print up to 3 decimal places: 2.365 Print up to 2 decimal places: 2.37 Print up to 7 decimal places: 2.3654789