Channi Studies

[C++] <iomanip> setprecision(n) 본문

C++/기타

[C++] <iomanip> setprecision(n)

Chan Lee 2023. 12. 10. 18:47

iomanip library를 활용하면 실수형 자료를 출력할 때, 소수점 몇번째 자리에서 반올림을 할 지 결정할 수 있습니다.

 

형식

// FORMAT

# include <iomanip>

cout << fixed << setprecision(num);

 

예시 코드

// Example Code

#include <iostream>
#include <iomanip>

using namespace std;

int main(){
    cout << fixed << setprecision(1);
    cout << 14.889 << endl;     // 14.9
    
    cout << fixed << setprecision(2);
    cout << 2.192 << endl;      // 2.19
    
    cout << fixed << setprecision(0);
    cout << 1.199 << endl;      // 1
}

 

setprecision(n)에서의 n은 소수점 이후 몇번째 자릿수에서 반올림을 할 것인지를 결정합니다.

n+1번째 자리에서 반올림을 한다고 생각하면 됩니다.

 

예를 들어 1이면 소수점 이후 1 + 1 = 2번째 자리에서 반올림이 되서, 14.889 → 14.9

2이면 소수점 이후 2 + 1 = 3번째 자리에서 진행되기 때문에, 2.192 → 2.19

0이면 1번째 자리이므로 1.199 → 1 입니다.