为什么printf()的不输出这个整数浮点数? [英] Why printf() isn't outputting this integer as float number?

查看:976
本文介绍了为什么printf()的不输出这个整数浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code:

#include <stdio.h>

int main()
{
    int i = 12345;
    printf("%f", i);

    return 0;
}

printf()函数将输出0.000000,应该不是printf()的跨preT包含在位I 作为一个浮点数?

推荐答案

这在技术上是未定义的行为,所以任何事情都有可能发生,比如什么@Art描述了他的答案。

This is technically undefined behaviour, so anything can happen, for instance what @Art describes in his answer.

下面这个答案,因此是一个解释,会发生什么,如果你试图打印12345为float假设的printf确实看到了正确的32位值。

This answer here is therefore an explanation as to what would happen if you tried to print 12345 as a float assuming printf indeed sees the correct 32-bit value.

让我们来分析您正在试图重新present数二进制重新presentation。

Let's analyze the binary representation for the number you are trying to represent.

使用 http://www.h-schmidt.net/FloatConverter/IEEE754.html 我们可以看到十进制数 12345 具有以下32位重presentation:

Using http://www.h-schmidt.net/FloatConverter/IEEE754.html we can see that the decimal number 12345 has the following 32-bit representation:

decimal      12345
hexadecimal  0x00003039

转换比特到比特到IEEE-754浮点数的32位值,该再presents:

Converted bit-to-bit to a IEEE-754 floating point 32-bit value, this represents:

float        1.7299E-41

让我们尝试打印:

let's try to print it:

#include <stdio.h>

int main() {
    printf("%f\n", 1.7299E-41);
    return 0;
}

这将打印:

0.000000

现在,让我们读的printf 手册页,因为这里找到:的 http://linux.die.net/man/3/printf

Now let's read printf man page, as found here: http://linux.die.net/man/3/printf

F,F

双论点是圆形,并在风格转换为十进制符号[ - ] ddd.ddd,其中的小数点字符后的数字位数等于precision规范。如果precision丢失,它被当作6;如果precision是明确为零,没有出现小数点字符。如果出现小数点,至少有一个数字出现之前。

The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it.

1.7299E-41 值不能再使用此标志与默认precision presented,所以你得到的结果确实是正确的值

The 1.7299E-41 value cannot be represented using this flag with the default precision, so the result you get is indeed the correct value.

这篇关于为什么printf()的不输出这个整数浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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