铸造INT为float [英] Casting int as float

查看:117
本文介绍了铸造INT为float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个int添加到浮动。我的code是:

I am trying to add an int to a float. My code is:

int main() {
   char paus[2];
   int millit = 5085840;
   float dmillit = .000005;
   float dbuffer;

   printf("(float)milit + dmillit: %f\n",(float)millit + dmillit);
   dbuffer = (float)millit + dmillit;
   printf("dbuffer: %f\n",dbuffer);

   fgets(paus,2,stdin);
   return 0;
 }

输出如下:

(浮点)millit + dmillit:5085840.000005结果
  dbuffer中:5085840.000000

(float)millit + dmillit: 5085840.000005
dbuffer: 5085840.000000

为什么有区别吗?我也注意到,如果我改变dmillit = 0.5,那么这两个输出是相同的(5085840.5),而这正是我所期望的。为什么是这样?谢谢!

Why is there a difference? I've also noticed that if I change dmillit = .5, then both outputs are the same (5085840.5), which is what I would expect. Why is this? Thanks!

推荐答案

这是您要使用precision太大的浮动。上printf函数它被浇铸到要打印一个双

the precision that you are trying to use is too big for a float. On the printf function it is being casted into a double to be printed.

查看网页。 IEEE 754浮点数运算以更好地理解这一点。

See the page IEEE 754 float calculator to better understand this.

这篇关于铸造INT为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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