I am getting a benign warning about possible data loss
warning C4244: 'argument' : conversion from 'const int' to 'float', possible loss of data
Question
I remember as if float has a larger precision than int. So how can data be lost if I convert from a smaller data type (int) to a larger data type (float)?
Because float
numbers are not precise. You cannot represent every possible value an int
can hold into a float
, even though the maximum value of a float
is much higher.
For instance, run this simple program:
#include <stdio.h>
int main()
{
for(int i = 0; i < 2147483647; i++)
{
float value = i;
int ivalue = value;
if(i != ivalue)
printf("Integer %d is represented as %d in a float\n", i, ivalue);
}
}
You'll quickly see that there are thousands billions of integers that can't be represented as float
s. For instance, all integers between the range 16,777,219 and 16,777,221 are represented as 16,777,220.
EDIT again Running that program above indicates that there are 2,071,986,175 positive integers that cannot be represented precisely as float
s. Which leaves you roughly with only 100 millions of positive integer that fit correctly into a float
. This means only one integer out of 21 is right when you put it into a float.
I expect the numbers to be the same for the negative integers.
On most architectures int
and float
are the same size, in that they have the same number of bits. However, in a float those bits are split between exponent and mantissa, meaning that there are actually fewer bits of precision in the float than the int. This is only likely to be a problem for larger integers, though.
On systems where an int
is 32 bits, a double
is usually 64 bits and so can exactly represent any int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With