728x90
반응형
기본적인 반올림, 올림, 내림
<cmath>가 필요하고
반올림은 round(숫자), 올림은 ceil(숫자), 내림은 floor(숫자)이다.
소수점 첫 번째 자리에서 반올림한다.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float num = 3.47;
cout << round(num) << "\n"; // 3
cout << ceil(num) << "\n"; // 4
cout << floor(num) << "\n"; // 3
}
소수점 n번째 자리에서 반올림, 올림, 내림
자리수를 조정하여 함수를 이용하고, 다시 자릿수를 원래대로 놓아주면 된다.
예를 들어 소수점 2번째 자리에서 반올림/올림/내림을 하려면 10을 곱한 후에 함수를 이용하고, 다시 10으로 나눠 반환한다.
소숫점이 0이면 따로 0을 표시하지 않는다.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float num = 3.06;
float num1 = round(10 * num) / 10;
float num2 = ceil(10 * num) / 10;
float num3 = floor(10 * num) / 10;
cout << num1 << "\n"; // 3.1
cout << num2 << "\n"; // 3.1
cout << num3 << "\n"; // 3
}
소수점이 0일 때도 소수점을 표시하려면?
fixed와 precision을 사용할 수 있다.
precision(n) : 정수부를 포함하여 n개의 숫자만 나타냄
fixed한 후 precision(n) : 소수부를 n자리까지 나타냄
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float num = 3.4356;
cout.precision(4);
cout << num << endl; // 3.436
cout << fixed; //소수점 고정
cout.precision(4);
cout << num << endl; // 3.4356
float num2 = 3.402;
cout.precision(2); // 3.40
cout << num2;
}
728x90
반응형
'Language > C++' 카테고리의 다른 글
[C++] advance 함수 (0) | 2024.01.30 |
---|---|
[C++] 문자열 split 함수 구현하기 (0) | 2023.03.14 |
[C++] PS할 때 전역변수를 써야 하는 경우 (0) | 2022.04.28 |
[C++] STL - 정렬 알고리즘 함수 (sort, stable_sort, binary_search) (0) | 2021.11.07 |
[C++] STL - 변경 알고리즘 함수 (copy, swap, transform, next_permutation) (0) | 2021.11.07 |