반응형

C++ cout 소수점 n표시 방법

#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번째 자리까지 표시해야 하는 경우가 있다.

 

만약 소수 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;를 쓰지 않는다면

#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

소수 3번째자리까지 표시가 아니라

숫자 갯수를 3개까지만 표시한다.

cout.precision(n)은 숫자 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';
	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.unsetf(ios::fixed) 해서 숫자에서 총 3자리가 출력된다.

cout << fixed 상태에서는 소수점 3자리까지 출력되었다.

 

 

 

cout.precision(n) 소수점 반올림이 되는 문제

 

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

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	

	double y = 1.77777777;
	
	cout << fixed;
	cout.precision(3);
	cout << y <<'\n';

	cout.precision(5);
	cout << y <<'\n';
	
	
}
1.778
1.77778

간혹가다 백준에서 소수를 출력해야하는 문제가 있다.

 

이런 경우 오차범위가 주어진다. 만약 소수점 자리수를 너무 적게 표시할 경우

 

오차범위에 걸려서 문제를 틀릴 수 있다.

 

이럴 경우를 대비해서 소수점 n번째까지 출력을 하라고 명시가 되지 않은 경우에는

 

그냥 소수점 자리수를 길게 출력하면 편하다.

 

소수는 컴퓨터로 계산할 때 항상 오차가 있다.

 

그래서 애초에 정답에 대해서 오차범위를 명시하고

 

오차범위 안에만 들어가면 답이 맞는다.

 

 

예를 들어 절대/상대 오차 10-2까지 허용한다고 하면

 

소수 5번째자릿수 까지 출력해버리면 편하다.

 

+ Recent posts