프로그래밍 언어/C++

[C++] cout 소수점 n자리까지 표시하기

ShovelingLife 2023. 9. 26. 17:15

일반적으로 아무 설정 없이 소수점을 표시하면

#include <bits/stdc++.h>
using namespace std;

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	double x = 3.333333333;
	
	cout << x << '\n';

}

3.33333

 

하지만 알고리즘 문제를 풀거나, 특정한 목적으로 소수점 표시를 적절하게 소수 n번째 자리까지 표시해야 하는 경우가 있다 cout<<fixed. 만약 소수 3번째 자리까지 표시를 하려면

 

cout 이전에

cout << fixed;

cout.precision(3);을 추가해주어야한다.

#include <bits/stdc++.h>
using namespace std;

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	double x = 3.333333333;
	
	cout << fixed;
	cout.precision(3);
	cout << x << '\n';
}

3.333

 

소수점 n번째 자리까지 출력할 때

cout << fixed;
cout.precision(n);
cout << x << '\n';

 

만약 cout<<fixed;를 쓰지 않는다면 소수 3번째자리까지 표시가 아니라 숫자 갯수를 3개까지만 표시한다. cout.precision(n)은 숫자 n개를 표시한다.

#include <bits/stdc++.h>
using namespace std;

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	double x = 3.333333333;
	
	cout.precision(3);
	cout << x << '\n';
}

3.33

 

근데 한번 이렇게 설정할 경우 이 코드 밑에 있는 모든 출력에서 n번 째 자리까지만 출력하게 된다.

#include <bits/stdc++.h>
using namespace std;

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	double x = 3.333333333;
	
	cout.precision(3);
	cout << x << '\n';
	cout << 1.234567 <<'\n';
}

3.33
1.23

 

설정을 변경 해주려면

#include <bits/stdc++.h>
using namespace std;
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	double x = 3.333333333;
	double y = 1.234567;
	

	cout.precision(3);
	cout << x << '\n';
	cout << y <<'\n';
	
	
	cout.precision(6);
	cout << x << '\n';
	cout << y <<'\n';
}

3.33
1.23
3.33333
1.23457

 

만약 cout.fixed를 초기화 하고싶다면 cout.unsetf(ios::fixed)를 추가해주면 된다.

#include <bits/stdc++.h>
using namespace std;

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	double x = 3.333333333;
	double y = 1.234567;
	
	cout << fixed;
	cout.precision(3);
	cout << x << '\n';
	cout << y <<'\n';
	
	cout.unsetf(ios::fixed);
	cout << x << '\n';
	cout << y <<'\n';
}

3.333
1.235
3.33
1.23

 

cout 소수점 표시, 소수점 n자리까지 표시하기 :: 딩코딩 : Computer Science 블로그 (tistory.com)