I'm wondering what int id = 5%2; does exactly and also look for similar things.
Reason:
I want to calculate by a number on which row / column the item should be standing.
[Example]
I have a grid which is 5x5.
If id = 05, it should be on the 1st row and the 5th column
If id = 10, it should be on the 2nd row and the 5th column
If id = 12, it should be on the 3rd row and the 2nd column
How you catch my drift!
(ps: feel free to edit my tags. Not sure what to put on this question)
The modulus ( %
in some C-derivative languages) is the remainder left over when one number is divided by another. So 38 % 6
is 2
( 38 / 6
is 6
with a remainder of 2
).
It's typically used for exactly the sort of thing you're asking about. If your 5x5 grid is:
col 1 2 3 4 5
row
1 1 2 3 4 5
2 6 7 8 9 10
3 11 12 13 14 15
4 16 17 18 19 20
5 21 22 23 24 25
then the row can be calculated as (x-1)/5+1
(that's integer division rather than floating point) and the column as (x-1)%5+1
:
x (x-1)/5+1 (x-1)%5+1
-- --------- ---------
5 1 5
10 2 5
12 3 2
The reason you initially subtract the one and then add it on is because modulus works best on zero-based numbers while yours are one-based. The subtract/add is to turn your scheme into zero-based before performing the modulus, then turning it back into one-based afterwards.
%
is the Modulus Operator , or in more common terms the remainder. So 5%2
would give you an id of 1
. Using this you can calculate the row
and column
values in your grid. So for example
id = 5;
column = (id - 1)%5 + 1;
row = (id - 1)/5 + 1;
The - 1
is because you seem to start off your rows at 1
instead of 0
.
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.