I think you realize that you casting minus to unsigned int
before assignment to float
. If you run the below code, you will get highly likely 4294965296
#include <stdio.h>
int main()
{
unsigned int a = 10;
unsigned int b = 20;
unsigned int c = 30;
printf("%u", -((a*b)*(c/3)));
return 0;
}
The -2000
to the right of your equals sign is set up as a signed
integer (probably 32 bits in size) and will have the hexadecimal value
0xFFFFF830
. The compiler generates code to move this signed integer
into your unsigned integer x
which is also a 32 bit entity. The
compiler assumes you only have a positive value to the right of the
equals sign so it simply moves all 32 bits into x
. x
now has the
value 0xFFFFF830
which is 4294965296
if interpreted as a positive
number. But the printf
format of %d
says the 32 bits are to be
interpreted as a signed integer so you get -2000
. If you had used
%u
it would have printed as 4294965296
.
#include <stdio.h>
#include <limits.h>
int main()
{
float d = 4294965296;
printf("d = %f\n\n", d);
return 0;
}
When you convert 4294965296
to float
, the number you are using is long to fit into the fraction part. Now that some precision was lost. Because of the loss, you got 4294965248.000000
as I got.
The IEEE-754 floating-point standard is a standard for representing
and manipulating floating-point quantities that is followed by all
modern computer systems.
bit 31 30 23 22 0
S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
The bit numbers are counting from the least-significant bit. The first
bit is the sign (0
for positive, 1
for negative). The following
8
bits are the exponent in excess-127 binary notation; this
means that the binary pattern 01111111 = 127
represents an exponent
of 0
, 1000000 = 128
, represents 1, 01111110 = 126
represents
-1
, and so forth. The mantissa fits in the remaining 24
bits, with
its leading 1
stripped off as described above. Source
As you can see, when doing conversion 4294965296
to float
, precision which is 00011000
loss occurs.
11111111111111111111100 00011000 0 <-- 4294965296
11111111111111111111100 00000000 0 <-- 4294965248