简体   繁体   English

在C / C ++中从double隐式转换为int64_t是什么

[英]What does implicit conversion from double to int64_t in C/C++

Could someone shed a light on the way this code behaves: 有人可以阐明此代码的行为方式:

double x = 9223371036854;
int64_t y1 = /* trunc */ (x * 1000000);
int64_t y2 = round(x * 1000000);
cout << y1 << " <= " << y2 << endl;
assert( y1 <= y2 ); // fail

This code fails due to y1 actually equals to 9223371036854000000 while y2 is 9223371036853999616 . 由于y1实际上等于9223371036854000000y292233710368539996169223371036854000000此代码失败。
After uncommenting trunc everything is ok (assertion verified). 取消注释后, trunc一切正常(确认为断言)。

Compiled by gcc-4.6.3-1ubuntu5 with g++ --std=c++0x x.cpp . 由gcc-4.6.3-1ubuntu5与g++ --std=c++0x x.cpp

Why int64_t(round(x * 1000000)) is less than int64_t(x * 1000000) where x is double ? 为什么int64_t(round(x * 1000000))小于int64_t(x * 1000000)其中xdouble

And why results of int64_t(trunc(x * 1000000)) is different from int64_t(x * 1000000) ? 为什么结果int64_t(trunc(x * 1000000))是由不同int64_t(x * 1000000)

I guess I found why it works like this ( y1 == 92233710368540000000 and assert fails). 我猜我发现了为什么它会这样工作( y1 == 92233710368540000000并断言失败)。

GCC optimized out run-time calculation of y1 without loosing precision which clearly happens in y2 . GCC优化了y1运行时计算,而不会降低在y2中明显发生的精度。 More intersting is that expression of literals have no such property 更有趣的是,文字表达没有这种属性

double x = 9223371036854;
int64_t y1 = /* trunc */ (x * 1000000);
int64_t y2 = round(x * 1000000);
cout << y1 << " <= " << y2 << endl;
assert( int64_t(9223371036854.0 * 1000000) <= int64_t(round(9223371036854e6)) ); // ok
assert( int64_t(x * 1000000) <= int64_t(round(x * 1000000)) ); // fails
assert( y1 <= y2 ); // fails

And if I'll move out 1e6 outside of expressions everything works as expected: 如果我将1e6移出1e6之外,那么一切都会按预期进行:

double x = 9223371036854.0 * 1000000;
int64_t y1 = /* trunc */ (x);
int64_t y2 = round(x);
cout << y1 << " <= " << y2 << endl;
assert( int64_t(x) <= int64_t(round(x)) ); // ok
assert( y1 <= y2 ); // ok

But probably my assumption about optimization is incorrect. 但是可能我对优化的假设是不正确的。

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

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