我非常怀疑使用浮点数进行除法, 这里是测试代码::
hi I have a big doubt of using floats for divisions, here the test code::
- (void)chuza { float option1 = 0; float option2 = 0; option1 = 100/50; option2 = 50/100; NSLog(@"option1 :: %f",option1); NSLog(@"option2 :: %f",option2); }所以, 我得到:
2012-10-19 16:21:45.405 Project[2023:14f03] option1 :: 2.000000 2012-10-19 16:21:45.405 Project[2023:14f03] option2 :: 0.000000所以我的问题是: 为什么浮动会像
so my question is: why would the float like when
分母>分子
denominator > numerator
但不喜欢
分子>分母??
numerator > denominator ??
谢谢!
推荐答案这看起来很像整数除法,因为您要除以两个整数.当除以两个整数时(大多数情况下,如果不是全部,则全部编程语言),将忽略除法的其余部分.
That looks a lot like integer division to me since you are dividing two integer numbers. When dividing two integers (in most if not all programming languages) ignores the remainder of the division.
考虑如何评估这条线.首先计算整数除法,然后将整数结果转换为浮点数,以存储在float变量中.
Think of how that line is being evaluated. First the integer division is calculated and then the integer result is cast to a float to be stored in the float variable.
请注意,整数根本不存储任何小数,因此即使是0.999,因为整数也将是0.这不是舍入的问题.
这也不关乎分母大于分子.尝试除以100/30,结果将为3,而不是3.33333 ..就像浮点除法一样.
您可以通过将数字强制转换为浮点数或确保它们是浮点数来解决此问题.
You can solve this by casting the numbers to floats or making sure they are float numbers.
option2 = ((float)50/(float)100);划分浮点数
option2 = 50.0f/100.0f;更多推荐
目标C的浮点数和除法数
发布评论