整数浮点数除以自身是否保证为1?

如果我写:

int x = /* any non-zero integer value */;
float y = x;
float z = y / y;

z保证正好是1。 f 吗?

5121 次浏览

If your C++ implementation uses IEEE754 then yes, this is guaranteed. (The division operator is required to return the best possible floating point value).

The 1.f4 exceptions for y / y, in general, not being 1.f are the cases when y is NaN, +Inf, -Inf, 0.f, and -0.f, or if you are on a platform where int is so wide that certain instances of it cannot be represented in a float without that float being set to +Inf or -Inf1.f5. Setting aside that final point, in your case that means that 1.f3 will produce the only exception.

IEEE754 is extremely common. But to check for sure, test the value of

std::numeric_limits<float>::is_iec559;

1A platform, for example, with a 128 bit int and an IEEE754 32 bit float would exhibit this behaviour for certain values of x.

No, not in all cases, even for IEEE754.

For example, with int x = 0;, you'll get NaN. (Live)