Ada*_*enz 9 c++ type-conversion
在Stanley B. Lippman的C ++ Primer中,“隐式转换”部分指出:
Run Code Online (Sandbox Code Playgroud)int ival; unsigned int ui; float fval; fval = ui - ival * 1.0;
ival转换为double,然后乘以1.0。结果转换为unsigned int,然后减去ui。结果转换为float,然后分配给fval。
但是我不这么认为:我认为实际上ival是将类型转换为double然后乘以1.0then ui,将类型unsigned int转换为double的情况并非相反,然后将乘法结果从转换为double的ui值中减去。最后将此最终double值转换为float并将其分配给fval。
为了确保我说的话:
ival = 5;
ui = 10;
fval = 7.22f;
dval = 3.14;
std::cout << typeid(ui - ival * 1.0).name() << std::endl; // double
std::cout << (ui - ival * 1.7) << std::endl; // 1.5 this proves that the unsigned int ui is converted to double not the contrary that is because C++ preserves precision. otherwise the decimal part is truncated.
Run Code Online (Sandbox Code Playgroud)
您的假设是正确的,而这本书是错误的。
fval = ui - ival * 1.0;
Run Code Online (Sandbox Code Playgroud)
可以改写成
fval = ui - (ival * 1.0);
Run Code Online (Sandbox Code Playgroud)
这样就给了我们
float = unsigned - (int * double)
Run Code Online (Sandbox Code Playgroud)
之所以(int * double)成为,是double因为通常的算术转换使我们
float = unsigned - double
Run Code Online (Sandbox Code Playgroud)
再次导致a double,我们将其分配double给float变量。
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |