여기에서 사전 정의된 소수 자릿수까지 일부 부동 소수점 숫자를 인쇄하는 방법을 살펴보겠습니다. C++에서는 cout과 함께 setprecision을 사용하여 이 단어를 수행할 수 있습니다. 이것은 C++의 iomanip 헤더 파일 아래에 있습니다.
예시 코드
#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;
} 출력
Print up to 3 decimal places: 2.365 Print up to 2 decimal places: 2.37 Print up to 7 decimal places: 2.3654789