#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';
}
이 코드를 추가하고 cin cout을 사용하면 기존의 scanf printf 속도보다 빨라집니다.
코테나 알고리즘 문제를 풀 때 입출력 시간을 절약하기 위해서
위 코드와 함께 cin cout을 이용해서 프로그래밍 하는 것이 좋습니다.
etc
입출력할 때 개행을 하려면
endl 대신 '\n' 을 사용해야 시간을 절약할 수 있습니다.
std::cout<<ans<<std::endl;
std::cout << ans << '\n';
stackoverflow 사이트에 게시된
ios::sync_with_stdio(false), cin.tie(0)와 관련한 글입니다.
이 글의 답변 내용 중
"The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization."