简体   繁体   English

为什么(C ++)从long long unsigned int转换为long double然后返回0

[英]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? 如果b可以包含a,那么为什么c为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. 嗯...它(网页)要求我提供更多详细信息,但是我不确定我还能说什么...我希望如果a适合b,那么它应该能够将其从b转换回c。

b can't necessarily contain a , only an approximation of it. b不一定包含a ,仅包含它的近似值。 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. long double的范围比unsigned long long范围大(因此max值更大),但是可能具有较少的尾数位来保存值的最高有效位,因此对于大值而言精度较低。

The maximum unsigned long long value is 2^N-1 where N is the number of bits; 最大unsigned long long值为2^N-1 ,其中N是位数。 probably 64. 大概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 . 如果long double尾数位数少于N ,则转换会将其舍入为两个最接近的可表示值之一,也许是2^N This is outside the range of unsigned long long , so converting back gives undefined behaviour. 这超出了unsigned long long的范围,因此转换回会产生不确定的行为。 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. 也许使用模块化算法将其减少到零(如果从整数类型转换会发生这种情况),但是原则上任何事情都可能发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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