面试问题打印一个浮点数 [英] interview question printing a floating point number

查看:112
本文介绍了面试问题打印一个浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是以下程序的输出,为什么?

What's the output of the following program and why?

  #include <stdio.h>
  int main()
  {
   float a = 12.5;
   printf("%d\n", a);
   printf("%d\n", *(int *)&a);
   return 0;
  }

我的编译器打印0和1095237632.为什么?

My compiler prints 0 and 1095237632. Why?

推荐答案

在这两种情况下你传递一个比特重新presenting浮点值,并将其打印为十进制。第二种情况是简单的情况下,这里的输出是相同的浮点数的底层再presentation。 (这是假设调用约定指定一个浮动的值传递相同的方法, INT 是,这不能保证。)

In both cases you pass a bits representing floating-point values, and print them as decimal. The second case is the simple case, here the output is the same as the underlying representation of the floating-point number. (This assumes that the calling convention specified that the value of a float is passed the same way an int is, which is not guaranteed.)

然而,在第一种情况下,当你路过一个浮动的printf A可变参数的功能是促进到双击。这意味着,传递的值将是64位,而的printf 将拿起它(或者垃圾)或者一半。在你的情况下,它显然已经拿起了32个最显著位,因为它们通常会在浮动双击演员。

However, in the first case, when you pass a float to a vararg function like printf it is promoted to a double. This mean that the value passed will be 64 bits, and printf will pick up either half of it (or perhaps garbage). In your case it has apparently picked up the 32 least significant bits, as they typically will be all zero after a float to double cast.

只是为了绝对清楚,在这个问题的code是的的有效C,因为它是非法的值传递给的printf 不匹配的格式说明。

Just to make it absolutely clear, the code in the question is not valid C, as it's illegal to pass values to printf that does not match the format specifier.

这篇关于面试问题打印一个浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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