따배씨++(2.3 부동소수점)

김동우·2021년 4월 2일
0

안녕하십니까. 김동우입니다.

일신상의 사유로 인해 당분간 노트는 코드에 담기로 했습니다.

이 점 유의하시어 보시면 감사하겠습니다.

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

int main () {

    using namespace std;

    float f(123456789.0f); //initilization, 10 significant digits
    double d(0.1);
    long double ld(3.141592);

    cout << setprecision(9) << endl;
    
    cout << 3.14 << endl;
    cout << 31.4e-1 << endl; // e = 10과 관련된 지수다. output = 3.14
    cout << 31.42e-2 << endl; // output = 0.3142, 기대값과 다름
    cout << 31.4e1 << endl; // output = 314.
    cout << 31.4e2 << endl; // output = 3140.

    cout << 1.0 / 3.0 << endl;

    cout << f << endl; // output : 123456792 
    // 실제 예상했던 결과와는 다른 값을 출력한다. 
    // 2진수로 저장을 하기 때문.

    cout << setprecision(19) << endl;
    cout << d << endl; // output : 0.1000000000000000056
    // 기대값과는 다른 결과

    double d1(1.0);
    double d2(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1);

    cout << d1 << endl; // output : 1.0
    cout << d2 << endl; // output : 0.999999999999999889

    double zero = 0.0;
    double posinf = 5.0 / zero;
    double neginf = -5.0 / zero;
    double nan = zero / zero;

    cout << posinf << endl; // output : inf
    cout << neginf << endl; // output : -inf
    cout << nan << endl; // output : nan
    // 위 셋과 비슷한 output이 나올 경우를 경계하자.

    cout << posinf << " " << isinf(posinf) << endl; // isinf = 1
    cout << neginf << " " << isnan(neginf) << endl; // isnan = 0
    cout << nan << " " << isnan(nan) << endl; // isnan = 1

    return 0;

    // 우리가 생각하는 수와 컴퓨터의 실제 연산과는 괴리가 있다.
    // 명심하고 코딩을 하도록 하자.
}

그럼 오늘 글은 이만 여기서 마치겠습니다.

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN