Why does 5/2 results in '2' even when I use a float? [duplicate]

最后都变了- 提交于 2019-12-18 09:43:47

问题


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!


回答1:


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).




回答2:


Why does 5/2 results in '2' even when I use a float?

Because you do not "use float". 5/2 is an integer division. Only its result (2) gets implicitly converted to a float to become a 2. (mind the dot).




回答3:


You should do proper type-casting .

float y = (float) 5/2 

Program will treat the numbers as int.
It is dividing two ints and writing this to float. Hence, answer is 2.0

You must type cast



来源:https://stackoverflow.com/questions/40264523/why-does-5-2-results-in-2-even-when-i-use-a-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!