我写了一个源代码来打印指定范围内的随机数。但它也返回一些负数,这正常吗?如果不正常,我该如何纠正?
#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);
}
最佳答案
如果你读到的随机数是负数(当然有可能),它的模也可以是负数。您应该使用无符号整数,以确保结果在您想要的范围内。
可以找到更多信息here .
关于c - 打印一个随机数返回一个负数。 (/开发/随机),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3649203/