int main()
{
double i=4;
printf("%d",i);
return 0;
}
Can anybody tell me why this program gives output of 0?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When you create a
doubleinitialised with the value4, its 64 bits are filled according to the IEEE-754 standard for double-precision floating-point numbers. A float is divided into three parts: a sign, an exponent, and a fraction (also known as a significand, coefficient, or mantissa). The sign is one bit and denotes whether the number is positive or negative. The sizes of the other fields depend on the size of the number. To decode the number, the following formula is used:1.Fraction × 2Exponent – 1023
In your example, the sign bit is 0 because the number is positive, the fractional part is 0 because the number is initialised as an integer, and the exponent part contains the value
1025(2 with an offset of 1023). The result is:1.0 × 22
Or, as you would expect,
4. The binary representation of the number (divided into sections) looks like this:Or, in hexadecimal,
0x4010000000000000. When passing a value toprintfusing the%dspecifier, it attempts to readsizeof(int)bytes from the parameters you passed to it. In your case,sizeof(int)is4, or 32 bits. Since the first (rightmost) 32 bits of the 64-bit floating-point number you supply are all0, it stands to reason thatprintfproduces0as its integer output. If you were to write:Then you might get
0 1074790400, where the second number is equivalent to0x40100000. I hope you see why this happens. Other answers have already given the fix for this: use the%fformat specifier andprintfwill correctly accept yourdouble.