c - 打印一个随机数返回一个负数。 (/开发/随机)

标签 c linux ubuntu random

我写了一个源代码来打印指定范围内的随机数。但它也返回一些负数,这正常吗?如果不正常,我该如何纠正?

#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/

相关文章:

c - 为什么 scanf() 在此代码中导致无限循环?

c - 请求非结构或 union 中的成员 ‘a’

r - 如何从 Rstudio 服务器使用 Oauth?

linux - 如何让两个docker容器可以互相ping通

无法在 sqlite 中找到实际结构

c - 嵌套结构 - 输入

linux - 在 shell 脚本中使用 passwd 命令

linux - emacs23 到 emacs24 : imap shell "Opening nnimap server...failed: Pseudo-terminal will not be allocated ..."

python - 如何在python中使用子进程模块

php - Codeigniter 虚拟主机 LAMP 配置故障排除