为什么 printf 输出 double 的随机值,int 输出 0.000000 的随机值? [英] Why does printf output random values for double and 0.000000 for int?

查看:43
本文介绍了为什么 printf 输出 double 的随机值,int 输出 0.000000 的随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个简单的问题,但它是在我编码时提出的,我想知道它现在是如何工作的.所以,我的第一个问题是当 printf 被赋予一个如下面的整数,但期望一个 %f 浮点值时,为什么它总是输出 0.000000?我在 linux 终端上的 GCC 中运行它.

I know this is a simple questions, but it came up when I was coding and I am wondering how it works now. So, my first question is that when printf is given an integer like below, but expecting a %f float value, why is it always outputting 0.000000? I am running this in GCC on linux terminal.

int main() {

int a = 2, b = 5, result = 0;
result = b/a*a;

printf("%f\n", result);
}
//Above printf statement outputs 0.000000 every time.

然后,当我使用下面的代码并在需要 %i 整数值时给 printf 一个双精度值时,输出总是随机/垃圾.

Then when I use the code below and give printf a double when it is expecting an %i integer value, the output is always random/garbage.

int main() {

double a = 2, b = 5, result = 0;
result = b/a*a;

printf("%i\n", result);
}
//Above printf statement outputs random numbers every time.

我完全理解上面的代码是不正确的,因为 printf 输出类型与我输入的不同,但我希望它对每种形式的错误采取相同的方式,而不是像这样改变.刚好引起了我的好奇,所以我想我会问.

I completely understand the above code is incorrect since the printf output type is not the same as I am inputting, but I expected it to act the same way for each form of error instead of changing like this. Just caught my curiosity so I thought I would ask.

推荐答案

基本上是因为如果您将组成小整数的位解释为双精度数,则它看起来像是 0 的双精度值.而如果您解释将小双精度值表示为整数的位,看起来更有趣.这是一个页面链接,该页面描述了如何使用位来表示双精度:http://en.m.wikipedia.org/wiki/IEEE_floating_point .通过这个链接和一点耐心,您实际上可以计算出给定双精度值将被解释为的整数值.

Basically because if you interpret the bits that make up a small integer as if they were a double, it looks like the double value for 0. Whereas if you interpret the bits that represent a small double value as an integer, it looks like something more interesting. Here is a link to a page that describes how the bits are used to represent a double: http://en.m.wikipedia.org/wiki/IEEE_floating_point . With this link and a little patience, you can actually work out the integer value that a given double would be interpreted as.

这篇关于为什么 printf 输出 double 的随机值,int 输出 0.000000 的随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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