줘이리의 인생적기

11. [C++] 부동소수점(float) 본문

공부/C++

11. [C++] 부동소수점(float)

줘이리 2021. 9. 24. 23:00
728x90

부동소수점에 대해서 알아보겠습니다.

 

사용할 때 주의해야 하는 것 중 하나입니다.

 

float 자료형 종류에 대해서 알아보고, 크기, 범위에 대해서 알아보겠습니다.

 

#include <iostream>
#include <limits>

using namespace std;

int main() {

	float a;
	double b;
	long double c;

	cout << "a size = " << sizeof(a) << endl;
	cout << "b size = " << sizeof(b) << endl;
	cout << "c size = " << sizeof(c) << endl;

	cout << "a max = " << numeric_limits<float>::max() << endl;
	cout << "b max = " << numeric_limits<double>::max() << endl;
	cout << "c max = " << numeric_limits<long double> ::max() << endl;

	cout << "a lowest = " << numeric_limits<float>::lowest() << endl;
	cout << "b lowest = " << numeric_limits<double>::lowest() << endl;
	cout << "c lowest = " << numeric_limits<long double> ::lowest() << endl;
  	
    return 0;
}


표현되는 자릿수가 아쉬울 경우가 있습니다.

그럴 때는 #include <iomanip>를 작성 후 setprecision을 사용하면 됩니다.

 

#include <iostream>
#include <limits>
#include <iomanip>

using namespace std;

int main() {
	float pi1 = 3.14159265359f;
	float pi2 = 3.14159265359;
	double pi3 = 3.14159265359;

	cout << pi1 << endl;
	cout << pi2 << endl;
	cout << pi3 << endl;

	cout << setprecision(10);
	cout << pi1 << endl;
	cout << pi2 << endl;
	cout << pi3 << endl;

	return 0;
}

setprecision을 사용하여 자릿수는 늘었지만 초기화한 값과는 다르게 나왔습니다.

 

주의해서 사용해야겠습니다.


nan이냐 infinite냐도 확인을 할 수 있어야겠죠

 

#include <cmath>를 포함하고 isnanisinf를 통해 알아보겠습니다

 

#include <iostream>
#include <limits>
#include <iomanip>
#include <cmath>

using namespace std;

int main() {
	double zero = 0.0;
	double pos_inf = 5.0 / zero;
	double neg_inf = -5.0 / zero;
	double nan = zero / zero;

	cout << pos_inf << endl;
	cout << neg_inf << endl;
	cout << nan << endl;

	cout << " pos_inf is nan ? = " << isnan(pos_inf) << endl;
	cout << " neg_inf is nan ? = " << isnan(neg_inf) << endl;
	cout << " nan is nan ? = " << isnan(nan) << endl;

	cout << " pos_inf is inf ? = " << isinf(pos_inf) << endl;
	cout << " neg_inf is inf ? = " << isinf(neg_inf) << endl;
	cout << " nan is inf ? = " << isinf(nan) << endl;

	return 0;
}

생각했던 대로 결과가 나왔네요