Suraj Jain
Suraj Jain

Reputation: 4536

Why Does Not My Program Works ???Float Casting

Nothing is printed as output but when i write while(x==3.1f) it works. i have thoroughly searched for an answer and i even find some but it is not really helping me. people have answered that using f as suffix make it float point default type is double. But how does it really works.. i want someone to explain me at the beginner level . I Have just started to learn C programming Language. Please Don't mark this question as answered before because i have already read all those answer and i am still not able to convince myself. I also want to know what does suffix f exactly do .. and how does a decimal is stored in binary . Why does not we simple give . as a another binary code and proceed as same as we did for integers . I may be asking something stupid . But i am really confused

include<stdio.h>

int main()
{
   float x = 3.1 ;
while(x==3.1)
{
printf("%f\n",x);
x=x-0.1;


}

return 0;

}

Upvotes: 1

Views: 65

Answers (1)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

3.1, in a C program, means the closest double to the decimal fraction 3.1. Assuming IEEE 754 binary floating point, the commonest implementation, its exact value is 3.100000000000000088817841970012523233890533447265625

When you assign it to x, it is converted to the closest float, 3.099999904632568359375.

Comparisons between a float and a double are done by converting the float to double and comparing doubles.

All conversions from float to double are exact, so the while condition would be true only if 3.099999904632568359375 were equal to 3.100000000000000088817841970012523233890533447265625

The exactness of float to double conversion is not just a matter of double taking up more space than float. An IEEE binary floating point number has three fields, a sign bit, a power-of-two exponent, and a significand. The float exponent and significand ranges are proper subsets of the corresponding double ranges.

On the wider questions, float and double are extremely compact and efficient, far more efficient than decimal scaled types such as Java's BigDecimal. The price is that they are in a binary version of scientific notation which cannot represent most decimal fractions exactly.

Upvotes: 1

Related Questions