I have written a source code to print random numbers within a specified limit.But it is also returning some negative numbers,is this normal?If not how do I rectify 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);
}
In case the random number you read is negative (which is certainly possible), the modulus of it can also be negative. You should use an unsigned integer in order to make sure the result is in the range you want.
More information can be found here.