안녕하십니까. 김동우입니다.
이번에는 관계연산자에 대해 노트를 적었습니다.
그럼 바로 코드부터 보시겠습니다.
#include <iostream>
#include <cmath>
#include <iomanip> // setprecision()
int main()
{
using namespace std;
int x, y;
cin >> x >> y;
cout << x << " " << y << '\n' << endl;
// relational operator
if (x == y) // 비교연산자, ==.
cout << "equal" << endl;
if (x != y) // 비교연산자(not) !=
cout << "Not equal" << endl;
if (x > y) // 크기비교
cout << "x is greater than y" << endl;
if (x < y) // 크기비교
cout << "x is less than y" << endl;
if (x >= y) // >=는 compiler의 입장에서 하나의 연산자
cout << "x is greater than or equal to y" << endl;
if (x <= y) // 위와 동일. (수리적 의미 : 작거나 같다.)
cout << "x is less than or equal to y" << endl;
/*
(input)
123
1234
123 1234
(output)
Not equal
x is less than y
x is less than or equal to y
if 문의 조합이기 때문에 부합하는 조건의 개수과 출력의 개수는 동일하다.
*/
double d1(100 - 99.99); // 0.001
double d2(10 - 9.99); // 0.001
if (d1 == d2)
cout << '\n' << "equal" << endl;
else
{
cout << '\n' << "Not equal" << endl;
if (d1 > d2)
cout << "d1 > d2" << endl;
else // because d1 != d2
cout << "d1 < d2" << endl;
}
// output : Not equal \n d1 > d2
const double epsilon = 1e-10;
// 임의상수. 값은 원하는대로 넣어도 된다.
// 값의 크기는 개발상황과 해당 상수의 사용처마다 다르다.
cout << '\n'<< std::abs(d1 - d2) << endl;
// output : 5.32907e-15
if(std::abs(d1 - d2) < epsilon)
cout << "Approximately equal" << endl;
else
cout << "Not equal" << endl;
// output : Approximately equal
cout << std::setprecision(20) << endl;
cout << d1 << " " << d2 << endl;
// output : 0.010000000000005115908 0.0099999999999997868372
// 보이는 것이 부동소수점 오차인데, 이와 같은 상황을 항상 유의하며 코딩해보자.
// 부동소수점 계산값의 오차를 어떻게 생각하느냐는 개인의 판단 문제이다.
// 이 정도면 같다, 혹은 완전 다른 값이다를 결정하는 것은 또한
// 개발목적과 상황이 기반이 될 것이다.
return 0;
}
그럼 이번 글은 이만 마치도록 하겠습니다. 감사합니다.