Pregunta

May I assume that (int)(float)n == n for any int n? At least I need this for non-negative, 31 bits values.

addendum. What about (int)(double)n ==n?

¿Fue útil?

Solución

No, you can't. For ints that can't be represented exactly by a float, this will fail.

(The reason: float is generally a 32-bit IEEE-754 floating-point value. It only has 24 bits of precision, the rest is reserved for the exponent and the sign. So if your integer has more significant binary digits than 23, and it doesn't happen to be a multiple of an appropriate power of two, then it can't be represented precisely as a float.)

addendum. What about (int)(double)n ==n?

It's the same. For ints that can't be represented as a double, the comparison won't always yield true. However, generally, int is not long enough to accomplish this -- the widely-accepted implementation of double is a 64-bit IEEE-754 floating-point number which has 53 bits of precision, whereas ints tend to be at most 32 bits long. But you can always try to repeat the experiment with a long or a long long and a double instead.

Here's a demo:

#include <stdio.h>

int main()
{
    int n = (1 << 24) + 1;

    printf("n == n: %d\n" , n == n);
    printf("n == (int)(float)n: %d\n", n == (int)(float)n);

    return 0;
}

This prints:

n == n: 1
n == (int)(float)n: 0
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top