-
-
- Setprecision trong C++ dùng để lấy số lượng chữ số trong phần thập phân sau dấu chấm động.
- Ví dụ: cout << setprecision(n) << f : in số thập phân f làm tròn đến n chữ số thập phân.
- Trường hợp nếu f có ít hơn n chữ số phần thập phân, ví dụ như f = 3.1 mà n = 4
thì khicout << setprecision(n) << f
sẽ chỉ in ra 3.1 mà không hiện đầy đủ 4 chữ số phần thập phân. - Do đó, nếu muốn in
f = 3.1
với chữ số thập phân thànhf = 3.1000
thì thêmfixed để
cố định in ra n chữ số phần thập phân.f = 3.1 n = 4 cout << setprecision(n) << fixed << f;// kết quả f=3.1000 - Ví dụ:
// vi du setprecision #include <iostream> #include <iomanip> // thu vien setprecision using namespace std; int main () { double f =3.14159; cout << setprecision(5) << f << '\n'; cout << setprecision(9) << f << '\n'; cout << setprecision(5) << fixed << f << '\n'; cout << setprecision(9) << fixed << f << '\n'; return 0; }
-
- Kết quả: