본문 바로가기

Algorithm

정수 오버플로, 실수 계산 유의점

정수 오버플로(Integer Overflow)

 

정수 오버플로(Integer Overflow)는 C언어 입문서에서도 자주 다루므로 익숙하다.

 

#include <iostream>


using namespace std;


int main()
{
	char a = 127;
	char b = -128;

	printf("a : %d b : %d\n", a, b);

	a += 1;
	b -= 1;

	printf("a : %d b : %d\n", a, b);

	return 0;
}

 

각 자료형마다 표현할 수 있는 수의 범위에는 한계가 존재한다.

그 한계를 넘어가면 정수 오버플로가 발생한다.

 

그러므로 각 자료형이 수를 어디까지 표현할 수 있는지 생각해보고 연산해줘야 한다.

 

 


실수 계산

 

(0.1 + 0.1 + 0.1) == 3은 True를 반환할까?

 

#include <iostream>

using namespace std;

int main()
{
	if ((0.1 + 0.1 + 0.1) == 0.3)
		cout << "True!" << "\n";
	else
		cout << "False!" << "\n";


	return 0;
}

 

놀랍게도 FALSE를 반환한다.

 

 

IEEE 754를 검색해보면 왜 이러는지 알 수 있다.

 

 

IEEE 754 - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search IEEE Standard for floating-point arithmetic The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point arithmetic established in 1985 by the

en.wikipedia.org

 

컴퓨터가 실수를 표현하는 특성 상, 오차가 존재할 수 밖에 없다.

비교하려는 a, b의 차를 계산하여 특정 숫자 이하의 결과가 나오는지 보고 같다, 틀리다를 판단해야겠다.

long long 형 데이터를 double 변수에 옮길 때도 조심해야 한다.

 


 

'Algorithm' 카테고리의 다른 글

알고리즘 공부 자료  (0) 2020.12.29