为什么5/2结果是'2',甚至当我使用浮动? [英] Why does 5/2 results in '2' even when I use a float?

查看:333
本文介绍了为什么5/2结果是'2',甚至当我使用浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我输入了下面的代码(没有编译问题或任何东西):

pre $ float $ y $ 5 /
printf(%f\\\
,y);

输出简单: 2.00000 p>

我的数学是不是错了?还是我错了/运营商?这意味着鸿沟不是吗?和5/2应该等于2.5?



任何帮助都非常感谢!

解决方案

5 int 2 是一个 int 。因此, 5/2 将使用整数除法。如果用 5.0f (或 2 )替换 5 2.0f ),使得其中一个 int sa float ,你会得到浮点数除法,并得到你所期望的 2.5 。您也可以通过明确地转换分子或分母(例如((float)5)/ 2 )来达到相同的效果。)


I entered the following code (and had no compiling problems or anything):

float y = 5/2;
printf("%f\n", y);

The output was simply: 2.00000

My math isn't wrong is it? Or am I wrong on the / operator? It means divide doesn't it? And 5/2 should equal 2.5?

Any help is greatly appreciated!

解决方案

5 is an int and 2 is an int. Therefore, 5/2 will use integer division. If you replace 5 with 5.0f (or 2 with 2.0f), making one of the ints a float, you will get floating point division and get the 2.5 you expect. You can also achieve the same effect by explicitly casting either the numerator or denominator (e.g. ((float) 5) / 2).

这篇关于为什么5/2结果是'2',甚至当我使用浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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