반응형
C++에서 실수를 출력할 때, 소수점 자릿수를 제어하는 방법으로
`cout.precision()` 과 `fixed`, `setprecision(n)` 가 자주 함께 등장한다.
이 둘의 차이를 명확히 이해하면, 원하는 출력 형식을 쉽게 다룰 수 있다.
기본 출력 방식
#include <iostream>
using namespace std;
int main() {
double pi = 3.1415926535;
cout << pi << endl; // 3.14159
}
기본적으로 실수를 출력할때는 소수점 아래 6자리까지 출력을 한다.
cout.precision
#include <iostream>
using namespace std;
int main() {
double pi = 3.1415926535;
cout.precision(4);
cout << pi << endl; // 3.142 (유효 숫자 4자리)
cout.precision(10);
cout << pi << endl; // 3.141592654 (유효 숫자 10자리)
}
- cout.precision(n)을 통해 전체 숫자의 자릿수를 정할 수 있다.
setprecision(n)
#include <iostream>
#include <iomanip> // setprecision
using namespace std;
int main() {
double pi = 3.1415926535;
cout << setprecision(4);
cout << pi << endl; // 3.142 (유효 숫자 4자리)
}
- setprecision(n)은 "전체 자릿수" 를 지정한다.
- 따라서 3.1415…를 유효 숫자 4자리로 → 3.142
fixed
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.1415926535;
cout << fixed;
cout.precision(4);
cout << pi << endl; // 3.1416
}
- fixed 를 쓰면 precision이 소수점 이하 자리수 의미로 바뀜
- 따라서 precision(4) → "소수점 아래 4자리까지"
반응형
'프로그래밍 언어 > C++' 카테고리의 다른 글
| C++ 연산자 우선 순위 (0) | 2025.09.21 |
|---|---|
| C++ 특정 문자 사이 값 입력받기 (0) | 2025.09.20 |
| C++ 지수 표기법 (0) | 2025.09.20 |
| C++ 표준 스트림 (0) | 2025.09.19 |
| C++ STL Map 사용법 (0) | 2023.04.14 |
댓글