简体   繁体   中英

Formula for number of rows from a x4 grid

Ok so I am currently setting up a grid, each row will have 4 objects. The number of rows must be calculated according to this constraint.

So if I had 15 objects, I need 4 rows. If i had 12 objects I need 3 rows.

Somehow I need some sort of mathematical formula that will perform and return this number. So when I say to the function I have x number of objects, it will return the number of rows.

Thanks for any help.

ceil(x / 4.0)

You want the ceiling, not the floor of the resultant value. Otherwise, you won't be able to fit say 15 into 4 rows.

Warning: readability swamp

floor((obj - 1) / 4) + 1

where obj is the number of objects in your question.

or even more concise:

floor((obj + 3) / 4)

One liner!

Floor usually comes with the language's integer division operator (eg, Java, C++), so it's probably shorter to implement.

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