본문 바로가기
개인공부/Algorithm(C, C++)

C++ iomanip 헤더, 소수점 자리 출력 fixed

by 저세상판단 2021. 7. 2.
반응형

#include <iomanip>를 포함시키면 setprecision(자리수)를 사용할 수 있다.

또한 fixed를 사용하여 원하고자 하는 자리수 까지 출력할 수 있다.

 


#include <iostream>
#include <iomanip>

using namespace std;

int main(){

	double a = 1.8888888888;
	
	//소수점 3번째 자리에서 반올림 
	cout <<  setprecision(3) << a << endl;
	
	//소수점 3번째 자리까지 표시, 즉 4번째에서 반올 림 
	cout << fixed << setprecision(3) << a << endl;
	return 0;
}

 

또한, 줄바꿈의 기능은 \nendl 두 가지로 할 수 있는데

\n의 경우 줄바꿈 기능만 하지만

endl의 경우 줄바꿈 후 버퍼를 비우는 flush를 수행하기 때문에

속도면에서 \n > endl 이다

반응형