简体   繁体   中英

Using floorf vs floor

I have the following situation in my code:

//maxiumumHeight and rowHeight are CGFloats
CGFloat rows = floorf(maximumHeight / rowHeight);
CGFloat height = (rows * rowHeight);

It works just fine, but I notice that when I use floor , it works fine also. I'm also confused about how to define rows , should it be an NSUInteger or CGFloat ?

It seems to work fine in all scenarios, but I have a little trouble understanding floating point math and was wondering what is the optimal way to do this code? Or does it matter?

floor is for double (which is same as CGFloat ) and floorf is for float (meaning it takes float arguments). This comes from ol' C stuff. Since you use CGFloat stick with floor . But, just in case, I would add a bit of tolerance, so change it to eg

CGFloat rows = floor ( ( maximumHeight + 0.5 ) / rowHeight );

assuming these values are always strictly positive.

Often you'd convert the number of rows to integer but since you calculate a UI height with it, which is also going to be used as CGFloat no need to use integers here. (Note if you are on watch CGFloat is float so there you'd want to use floorf but FWIW on many architectures floor and floorf are one and the same).

Not sure if this is what is troubling you, but floor rounds down to nearest int. So if you have eg 100 pixels available and you want a row to have 20 pixels, you will have

100 / 20 = 5

rows. What if you want it to be 21 pixels? Then

100 / 21 = 4.76

Now you need to decide. If you are going to insert 4 rows here you use floor since

floor ( 4.7 ) = 4.0

and note that, since you use only 4 rows, the height of each row will be

100 / 4 = 25

pixels, a bit more (since you use less rows) than the 21 you hoped for.

If you in stead want to use 5 rows then use ceil or ceiling since

ceil ( 4.7 ) = 5.0

and here note that since you use more rows the height will be

100 / 5 = 20

pixels. So if the 21 you hoped for is a maximum you'd use ceil in this particular example. If it is a minimum likewise you'd use floor .

Sometimes you may get funny and unexpected values, something like

100 / 20 = 4.999999999

which is why I'd add a bit of tolerance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM