[英]Why is implicit conversion from pair<int64_t,int64_t> to pair<int,int> allowed?
[英]What does implicit conversion from double to int64_t in C/C++
有人可以阐明此代码的行为方式:
double x = 9223371036854;
int64_t y1 = /* trunc */ (x * 1000000);
int64_t y2 = round(x * 1000000);
cout << y1 << " <= " << y2 << endl;
assert( y1 <= y2 ); // fail
由于y1
实际上等于9223371036854000000
而y2
是9223371036853999616
, 9223371036854000000
此代码失败。
取消注释后, trunc
一切正常(确认为断言)。
由gcc-4.6.3-1ubuntu5与g++ --std=c++0x x.cpp
。
为什么int64_t(round(x * 1000000))
小于int64_t(x * 1000000)
其中x
是double
?
为什么结果int64_t(trunc(x * 1000000))
是由不同int64_t(x * 1000000)
我猜我发现了为什么它会这样工作( y1 == 92233710368540000000
并断言失败)。
GCC优化了y1
运行时计算,而不会降低在y2
中明显发生的精度。 更有趣的是,文字表达没有这种属性
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
如果我将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
但是可能我对优化的假设是不正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.