0

I want to wrap a random number using modulo, so that values exceeding 11 starts over from 0 and greater. However, i would also like numbers less than 0 to dividend 11 or less.

Please correct me if i'm wrong, but as far as i can tell the modulo operator only dividends values exceeding the divisor. If so, how can i write code that also dividends values less than 0?

0

2 Answers 2

1

One crude way:

while (x > 11) x -= 11;
while (x < 0) x += 11;

The first could be replaced with a modulo operation.

0
2

Simply use modulo

#include <stdio.h>

int main(){
   for (int i = -23;i<23;i++) printf("%d    %d\n",i,i%11);
   return 0;
}

all modern C variants should work the same way https://en.wikipedia.org/wiki/Modulo_operation (result have same sign as divident):

-23 -1
-22 0
-21 -10
-20 -9
-19 -8
-18 -7
-17 -6
-16 -5
-15 -4
-14 -3
-13 -2
-12 -1
-11 0
-10 -10
-9  -9
-8  -8
-7  -7
-6  -6
-5  -5
-4  -4
-3  -3
-2  -2
-1  -1
0   0
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  10
11  0
12  1
13  2
14  3
15  4
16  5
17  6
18  7
19  8
20  9
21  10
22  0

for new formulation of request fixed by @Gerben suggestion

if you want monotonic 0..10 sequencies, add 11, if result is negative :

#include <stdio.h>

int main(){
for (int i = -23;i<23;i++)
    {
    int x= i%11 ;
    x += x<0?11:0;
    printf("    %d  %d\n",i,x);
    };
return 0;
}

results in

-23 10
-22 0
-21 1
-20 2
-19 3
-18 4
-17 5
-16 6
-15 7
-14 8
-13 9
-12 10
-11 0
-10 1
-9  2
-8  3
-7  4
-6  5
-5  6
-4  7
-3  8
-2  9
-1  10
0   0
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  10
11  0
12  1
13  2
14  3
15  4
16  5
17  6
18  7
19  8
20  9
21  10
22  0
3
  • Thanks for your feedback. However, this seems to produce a different result than what i asked for.
    – Erik
    Jun 22, 2018 at 15:35
  • If the value is negative, add 11.
    – Gerben
    Jun 22, 2018 at 17:28
  • fixed by @Gerben suggestion
    – gilhad
    Jun 22, 2018 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.