从一些printf的输出错 [英] Wrong output from printf of a number

查看:198
本文介绍了从一些printf的输出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
       double i=4;
       printf("%d",i);
       return 0;
}

任何人能告诉我,为什么这个节目给人的输出0?

Can anybody tell me why this program gives output of 0?

推荐答案

当你创建一个双击的值初始化 4 ,其64位是按照 IEEE-754标准以双$充满p $ pcision浮点数。一个浮点分为三个部分:标志的,一个的指数的和的分数的(也称为的尾数系数尾数的)。符号为一个比特和表示数是正还是负。其他字段的大小取决于数的大小。要取消code的数量,计算公式为:

When you create a double initialised with the value 4, 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 分数的&倍; 2 指数的 - 1023

1.Fraction × 2Exponent - 1023

在您的例子中,符号位是0,因为数是正的,小数部分是0,因为数被初始化为一个整数,并且指数部分包含值 1025 (2与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倍; 2 2

或者,正如你所期望的, 4 。数字的二进制重新presentation(分成部分)如下:

Or, as you would expect, 4. The binary representation of the number (divided into sections) looks like this:

0 10000000001 0000000000000000000000000000000000000000000000000000

或者十六进制, 0x4010000000000000 。当使用%d个符,它将尝试读取传递一个值的printf 的sizeof( INT)从你传递给它的参数字节。在你的情况,的sizeof(INT) 4 或32位。因为第一个(最右边)32您提供全 0 ,它按理说,的printf 产生 0 作为整数输出。如果你写的:

Or, in hexadecimal, 0x4010000000000000. When passing a value to printf using the %d specifier, it attempts to read sizeof(int) bytes from the parameters you passed to it. In your case, sizeof(int) is 4, or 32 bits. Since the first (rightmost) 32 bits of the 64-bit floating-point number you supply are all 0, it stands to reason that printf produces 0 as its integer output. If you were to write:

printf("%d %d", i);

然后,你可能会得到 0 1074790400 ,其中第二个数字是等同于 0x40100000 。我希望你明白为什么会这样。其他答案已经给修复了这一点:使用%F 格式说明和的printf 将正确地接受你的双击

Then you might get 0 1074790400, where the second number is equivalent to 0x40100000. I hope you see why this happens. Other answers have already given the fix for this: use the %f format specifier and printf will correctly accept your double.

这篇关于从一些printf的输出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆