Precision of multiplication by 1.0 and int to float conversion(乘以 1.0 和 int 到浮点转换的精度)
问题描述
假设条件 (int)(i * 1.0f) == i
对于任何整数 i
为真是否安全?
Is it safe to assume that the condition (int)(i * 1.0f) == i
is true for any integer i
?
推荐答案
没有.
如果 i
足够大以至于 int(float(i)) != i
(假设 float 是 IEEE-754 单精度,i = 0x1000001
足以证明这一点)那么这是错误的,因为乘以 1.0f
会强制转换为 float
,即使随后的乘法不会改变值.
If i
is sufficiently large that int(float(i)) != i
(assuming float is IEEE-754 single precision, i = 0x1000001
suffices to exhibit this) then this is false, because multiplication by 1.0f
forces a conversion to float
, which changes the value even though the subsequent multiplication does not.
但是,如果 i
是一个 32 位整数并且 double
是 IEEE-754 double,那么 是真的 int(i*1.0) == i
.
However, if i
is a 32-bit integer and double
is IEEE-754 double, then it is true that int(i*1.0) == i
.
为了完全清楚,乘以 1.0f
是准确的.可能不是从 int
到 float
的转换.
Just to be totally clear, multiplication by 1.0f
is exact. It's the conversion from int
to float
that may not be.
这篇关于乘以 1.0 和 int 到浮点转换的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:乘以 1.0 和 int 到浮点转换的精度


基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01