繁体   English   中英

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

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

我有这样的程序:

#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;
}

产生这样的输出:

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

如果b可以包含a,那么为什么c为0?

嗯...它(网页)要求我提供更多详细信息,但是我不确定我还能说什么...我希望如果a适合b,那么它应该能够将其从b转换回c。

b不一定包含a ,仅包含它的近似值。 long double的范围比unsigned long long范围大(因此max值更大),但是可能具有较少的尾数位来保存值的最高有效位,因此对于大值而言精度较低。

最大unsigned long long值为2^N-1 ,其中N是位数。 大概64。

如果long double尾数位数少于N ,则转换会将其舍入为两个最接近的可表示值之一,也许是2^N 这超出了unsigned long long的范围,因此转换回会产生不确定的行为。 也许使用模块化算法将其减少到零(如果从整数类型转换会发生这种情况),但是原则上任何事情都可能发生。

暂无
暂无

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

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