Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

of objective C floats and divisions

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

}

So, I get:

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

but doesnt like

numerator > denominator ??

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...