c语言中含负数的随机数,c
我已经写了一个源代码来打印指定范围内的随机数.但是它也返回一些负数,这正常吗?如果没有,我该如何纠正?
#include
#include
#include
#include
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.
标签:random,ubuntu,c-3,linux
来源: .html