Printing a random number returns a negative number. (/ Dev / urandom)

I wrote the source code for printing random numbers within a given limit. But it also returns some negative numbers, is that normal? If not, how to fix it?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main( int argc, char* argv[])

{        

    int fd, n;
    fd = open("/dev/urandom", O_RDONLY);
    if(fd == -1)
    printf("ERROR: Cannot Open %s\n",argv[1]);

    read(fd, &n, sizeof(n));                      //n=random number
    printf("%d\n",1+n%6);                         //limiting n 

    /* 1+n%6 should give me random numbers only between
       1-6(correct me if I'm wrong),
       but somehow it even gives negative numbers*/        

    close(fd);

}
+3
source share
3 answers

If the random number you are reading is negative (which is certainly possible), its modulus can also be negative. You must use an unsigned integer to ensure that the result is in the range you need.

More information can be found here .

+1
source

1 + n % 6 0-6. , .

#include <stdio.h>

int main(int argc, char* argv[]) {
  printf("%d\n", 1 + (-23) % 6);

  return 0;
}
+1

, , modulo

c=a%b

c [0, b-1].

, K & R (. 39, 2- .):

x% y , x y, , , y x.

, :

c = sign(a) * ( abs(a)%abs(b) )

( (a) = -1 a < 0 +1 a >= 0)

, - C. , GCC v4.4.1.

. C.

+1

Source: https://habr.com/ru/post/1763392/


All Articles