加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 从unsigned long long到double转换,反之亦然更改值

发布时间:2020-12-16 03:15:53 所属栏目:百科 来源:网络整理
导读:当写一个C代码时,我突然意识到我的数字被错误地从double转换为unsigned long long. 具体来说,我使用以下代码: #define _CRT_SECURE_NO_WARNINGS#include iostream#include limitsusing namespace std;int main(){ unsigned long long ull = numeric_limitsu
当写一个C代码时,我突然意识到我的数字被错误地从double转换为unsigned long long.

具体来说,我使用以下代码:

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <limits>
using namespace std;

int main()
{
  unsigned long long ull = numeric_limits<unsigned long long>::max();
  double d = static_cast<double>(ull);
  unsigned long long ull2 = static_cast<unsigned long long>(d);
  cout << ull << endl << d << endl << ull2 << endl;
  return 0;
}

Ideone live example.

当我的计算机上执行此代码时,我有以下输出:

18446744073709551615
1.84467e+019
9223372036854775808
Press any key to continue . . .

我预计第一和第三个数字是完全一样的(就像Ideone一样),因为我确信长双倍需要10个字节,并将尾数存储在其中8个.我会明白第三个数字是否与第一个数字相比被截断 – 只是为了我的浮点数字格式错误.但这里的价值观是两倍的!

所以,主要的问题是:为什么?那我怎么能预测这种情况呢?

一些细节:我在Windows 7上使用Visual Studio 2013,为x86编译,sizeof(long double)== 8为我的系统.

解决方法

18446744073709551615不是双精确的(在IEEE754中).这并不意外,因为64位浮点显然不能表示64位中可表示的所有整数.

根据C标准,实施定义是否使用下一个最高或下一个最低的双重值.显然在您的系统上,它会选择下一个最高值,这似乎是1.8446744073709552e19.您可以通过输出更多数字的精度来确认.

请注意,这大于原始数字.

当您将此double转换为整数时,行为由[conv.fpint] / 1覆盖:

A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is,the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.

所以这个代码可能会导致undefined behaviour.当未定义的行为发生时,任何事情都可能发生,包括(但不限于)伪造的输出.

这个问题最初是用双倍的倍,而不是双倍.在我的gcc上,长双倍的情况下正常运行,但是在OP的MSVC上,它给出了相同的错误.这可以由gcc使用80位长双倍解释,但MSVC使用64位长双倍.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读