of objective C floats and divisions

后端 未结 3 1191
悲&欢浪女
悲&欢浪女 2020-12-12 06:03

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/         


        
相关标签:
3条回答
  • 2020-12-12 06:21

    It's treating your numbers as integers, performing the division and then putting the result into a float.

    Try this option2 = 50.0f/100;

    0 讨论(0)
  • 2020-12-12 06:30

    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.

    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.

    Note that integers don't store any decimals at all so even 0.999 as an integer would be 0. It's not a problem about rounding.

    It's also not about the denominator being bigger than the numerator. Try dividing 100/30 and the result will be 3, not 3.33333.. as it would be for float division.

    You can solve this by casting the numbers to floats or making sure they are float numbers.

    Casting

    option2 = ((float)50/(float)100);
    

    Dividing floats

    option2 = 50.0f/100.0f;
    
    0 讨论(0)
  • 2020-12-12 06:33

    Neither 100 nor 50 are floats, they're integers. That means you're doing integer division and assigning the result to a floating point variable. Since integer division truncates (throws away fractional results), 50/100 yields 0. 100 is divisible by 50, which which is why you get the 2.000000 result. Try your program with 75 and 100, and you'll see there's more at work than just which direction the division goes.

    0 讨论(0)
提交回复
热议问题