简体   繁体   中英

Why (c++) casting from long long unsigned int to long double and back produces 0

I have such program:

#include "stdafx.h"
#include <iostream>

using namespace System;
using namespace std;

typedef long long unsigned int T_num;
typedef long double T_ld;


int main(array<System::String ^> ^args) {
    T_num a = numeric_limits<T_num>::max();
    T_ld b = numeric_limits<T_ld>::max();
    if ( b > a ) {
        cout << "decimal is bigger than integer" << endl;
    } else {
        cout << "integer is bigger than decimal" << endl;
    }
    T_num c;
    b = a;
    c = floor(b);
    if ( c == a) {
        cout << "OK" << endl;
    } else {
        cout << "dupa" << endl;
        cout << c << endl;
        cout << a << endl;
        cout << b << endl;
    }
    system("pause");
    return 0;
}

Which produces such output:

decimal is bigger than integer
dupa
0
18446744073709551615
1.84467e+019
Press any key to continue . . .

If b can contain a, so why c is 0?

Hmm... it (web page) asks me to provide more details but I am not sure what more could I say... I expect that if a fits in b then it should be able to convert it back from b to c.

b can't necessarily contain a , only an approximation of it. long double has a larger range than unsigned long long (hence a larger value of max ) but might have fewer mantissa bits to hold the most significant bits of the value, giving less precision for large values.

The maximum unsigned long long value is 2^N-1 where N is the number of bits; probably 64.

If long double has fewer then N mantissa bits, then conversion will round this to one of the two nearest representable values, perhaps 2^N . This is outside the range of unsigned long long , so converting back gives undefined behaviour. Perhaps it's being reduced using modular arithmetic to zero (as would happen if converting from an integer type), but in principle anything could happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM