目标C的浮点数和除法数 [英] of objective C floats and divisions

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

问题描述

我非常怀疑使用浮点数进行除法, 这里是测试代码::

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的浮点数和除法数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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