整数除法后浮点数为0 [英] Float is 0 after integer division

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

问题描述

这可能是一个简单的解决方案,但我无法修复它。

It might be a simple solution but I can not fix it.

我正在划分2个整数:

finishedGameFinalScore = [score integerValue];
CGFloat interval = 2/finishedGameFinalScore;
NSLog(@"interval = %f",interval);

日志返回 0.000000

小数位是否有限制?我需要保留小数结果。

Is there a limit for decimal places? I need to preserve the decimal result.

谢谢
Shani

Thanks Shani

推荐答案

您的代码不起作用的原因是您将整数除以另一个整数,然后将结果转换为浮点数。

The reason your code doesn't work is that you're dividing an integer by another integer and then casting the result to a float.

所以你有2(一个整数)和一些其他数字(也是一个整数)。然后用这个数除以2 - 这可能大于2.假设它是3。

So you have 2 (an integer) and some other number (also an integer). Then you divide 2 by this number - which is probably greater than 2. Let's say it's 3.

整数看到2/3他就像0.66666667?Pshh,无论如何都没有人需要小数点之后的任何东西。所以他截断了它。你只有0。

Integer sees 2/3 and he's like "0.66666667? Pshh, no one ever needs anything after the decimal point anyway". So he truncates it. You just have 0.

然后整数给出先生 float 和先生浮动非常乐意获得一个号码!他都喜欢yay,0!我将添加所有重要的数字。这就是你最终获得0.0000000的方式。

Then Integer gives the number to Mr. float and Mr float is super happy to get a number! He's all like "yay, a 0! I'm going to add ALL OF THE SIGNIFICANT DIGITS". And that's how you end up with 0.0000000.

所以是的,先投入浮动。甚至是双倍!

So yeah, just cast to a float first. Or even a double!

这篇关于整数除法后浮点数为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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