본문 바로가기

관계연산자 Relational Operators 본문

💘 C++/연산자들

관계연산자 Relational Operators

Hyonii 2022. 1. 3. 00:09

관계연산자 Relational Operator

C++에는 여섯 가지 관계 연산자(or 비교 연산자)가 있다.

Operator Symbol Form Opertation
Greater than > x>y true if x is greater than y, false otherwise
Less than < x<y true if x is less than y, false otherwise
Greater than or equals >= x>=y true if x is greater than or equal to y, false otherwise
Less than or equals <= x<=y true if x is less than or equal to y, false otherwise
Equality == x==y true if x equal y, false otherwise
Inequality != x!=y true if x does not equal y, false otherwise

각 연산자는 bool 값 true(1) 또는 false(0)을 반환한다.

 

위 연산자들은 정수 비교 시 간단한게 사용할 수 있다.

 

부동소수점 숫자 비교 Comparison of floating point values

관계 연산자를 사용해서 부동 소수점 숫자를 비교하는 것은 위험하다.

부동 소수점 숫자의 반올림 오류때문에 예상치 못한 결과가 나타날 수 있기 때문.

 

#include <iostream>
using namespace std;

int main()
{
    double d1(100 - 99.99); //0.001
    double d2(10 - 9.99);   //0.001
    
    if (d1 == d2)
        cout << "equal" << endl;
    else
        cout << "Not equal" << endl;
        
    return 0;
}

//This produces the result:
//Not equal

사람이 봤을 때 d1과 d2는 같은 0.001인데 같지 않다고 나온다.

 

부동 소수점에서는 관계연산자 비교 할 때 같아야 할 것이 같지 않게 나오는 경우가 있다.
크기를 볼 때는 cmath include 해야한다.

아주 미세한 차이가 있다.

이 정도 차이는 같다고 컴퓨터에게 알려주고 싶으면 오차의 한계를 미리 정의 하는 방법이 있다.

 

이렇게 범위를 줄 수 있다. 이때 epsilon은 조절 가능하다.

epsilon 을 수정해보면

 

d1과 d2의 차이의 절대값이 epsilon 보다 크기 때문에 Not equal.

 

epsilon은 그 때 그 때 푸는 문제에 따라 다르게 결정하면 된다.

 

Comments