Chinaunix

标题: 面试宝典中的一题 能否分析下 [打印本页]

作者: duanius    时间: 2008-09-08 20:05
标题: 面试宝典中的一题 能否分析下
#include<stdio.h>
int main(){
printf("%f",5);
printf("%d",5.01);
}
求输出结果

这道题答案是0.000000  以及一个大数   但我不是很清楚过程  
第一个结果程序在栈上多读了4个字节  但怎么知道高4位就一定是零呢
第二个输出应该是输出浮点数的低4位吧   为啥是大数呢?
作者: scutan    时间: 2008-09-08 20:19
浮点数有它自己的一个格式。这个具体是有标准的。
作者: duanius    时间: 2008-09-08 20:24
呃。。。我好像还是不懂   
btw 我挺讨厌浮点数的
作者: cugb_cat    时间: 2008-09-08 20:28
原帖由 duanius 于 2008-9-8 20:24 发表
呃。。。我好像还是不懂   
btw 我挺讨厌浮点数的

看看书或文档。。。
作者: duanius    时间: 2008-09-08 20:30
原帖由 cugb_cat 于 2008-9-8 20:28 发表

看看书或文档。。。

ok。。。。  再次bs有碍和谐的浮点数
作者: zszjxh    时间: 2008-09-08 21:23
gcc下第二个打印每次运行的结果不一样呢?

[ 本帖最后由 zszjxh 于 2008-9-8 22:39 编辑 ]
作者: poor-man    时间: 2008-09-08 23:14
标题: 修改一个模式就清楚了
改成这样子可能你就能想明白了

  1. #include<stdio.h>
  2. int main()
  3. {
  4. printf("%f,",5);
  5. printf("%f,",(int)5);
  6. printf("%d,",5.01);
  7. printf("%d",(double)5.01);
  8. }
复制代码

作者: timespace    时间: 2008-09-09 00:24
浮点格式标准IEEE754,wiki简介http://en.wikipedia.org/wiki/IEEE_754

[ 本帖最后由 timespace 于 2008-9-9 01:00 编辑 ]

IEEE754.pdf

114.54 KB, 下载次数: 91


作者: honey709    时间: 2008-09-09 09:29
sigh

谢谢了。。。。。。。。。。。。。。。。。。。。。。
作者: senic    时间: 2008-09-09 11:19
原帖由 poor-man 于 2008-9-8 23:14 发表
改成这样子可能你就能想明白了

#include
int main()
{
printf("%f,",5);
printf("%f,",(int)5);
printf("%d,",5.01);
printf("%d",(double)5.01);
}



-0.408503,-0.408503,1889785610,1889785610

-0.057777,-0.057777,1889785610,1889785610

-1.400063,-1.400063,1889785610,1889785610

-0.008594,-0.008594,1889785610,1889785610

-0.009753,-0.009753,1889785610,1889785610
作者: poor-man    时间: 2008-09-10 09:56
标题: 回复 #10 senic 的帖子
这不就对了吗?
第一列和第二列相等,第三列第四列相等,说明啥?
说明printf("%f,",5)和printf("%f,",(int)5)等效,printf("%d,",5.01)和printf("%d",(double)5.01)等效呗,换句话说,系统将“5”解释成了int,将“5.01”解释成了double类型;至此,你应该知道他们在内存中的样子了,都知道他们在内存中的样子,那也应该知道系统怎么处理他们的了?如果不明白,请看书吧。
作者: Visame    时间: 2008-09-10 11:23
这种题目没有太大意义。

  1. If a conversion specification is invalid, the behavior is undefined.If any argument is
  2. not the correct type for the corresponding conversion specification, the behavior is
  3. undefined.
复制代码

作者: 以泪洗面    时间: 2008-09-10 15:30
  1. C has two simple rules that control conversion of function arguments: (1) integer values shorter than
  2. an int are converted to int; (2) floating-point values shorter than a double are converted to double.
  3. All other values are left unconverted. It is the programmer’s responsibility to ensure that the arguments to
  4. a function are of the right type.
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2