관계연산자 Relational Operators 본문
관계연산자 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인데 같지 않다고 나온다.
아주 미세한 차이가 있다.
이 정도 차이는 같다고 컴퓨터에게 알려주고 싶으면 오차의 한계를 미리 정의 하는 방법이 있다.
epsilon 을 수정해보면
epsilon은 그 때 그 때 푸는 문제에 따라 다르게 결정하면 된다.
'💘 C++ > 연산자들' 카테고리의 다른 글
이진수 Binary Numbers (0) | 2022.01.07 |
---|---|
논리 연산자 Logical Operators (0) | 2022.01.03 |
Sizeof, 쉼표 연산자, 조건부 연산자 (0) | 2022.01.02 |
증감 연산자 increment decrement operators (0) | 2021.12.31 |
산술 연산자 arithmetic operators (0) | 2021.12.29 |
Comments