如何从用C全系列int的随机数? [英] How to generate a random number from whole range of int in C?

查看:172
本文介绍了如何从用C全系列int的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

unsigned const number = minimum + (rand() % (maximum - minimum + 1))

我知道如何(容易)生成一个范围内的随机数,如从0到100但是,我们从全系列 INT <随机数 / code>(假设的sizeof(int)的== 4 ),也就是从 INT_MIN INT_MAX ,既包容?

I know how to (easily) generate a random number within a range such as from 0 to 100. But what about a random number from the full range of int (assume sizeof(int) == 4), that is from INT_MIN to INT_MAX, both inclusive?

我并不需要这个密码之类,而是一个近似均匀的分布将是很好的,我需要的很多的这些数字。

I don't need this for cryptography or the like, but a approximately uniform distribution would be nice, and I need a lot of those numbers.

目前我使用的方法是产生范围内4的随机数从0到255(含),并做一些乱七八糟的铸造和位操作。我不知道是否有更好的办法。

The approach I'm currently using is to generate 4 random numbers in the range from 0 to 255 (inclusive) and do some messy casting and bit manipulations. I wonder whether there's a better way.

推荐答案

在我的系统 RAND_MAX 32767这是15位。因此,对于一个32位的无符号只需拨打三次转变,或者,面罩等。

On my system RAND_MAX is 32767 which is 15 bits. So for a 32-bit unsigned just call three times and shift, or, mask etc.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void){
    unsigned rando, i;
    srand((unsigned)time(NULL));
    for (i = 0; i < 3; i++) {
        rando = ((unsigned)rand() << 17) | ((unsigned)rand() << 2) | ((unsigned)rand() & 3);
        printf("%u\n", rando);
    }
    return 0;
}

程序输出:

3294784390
3748022412
4088204778

这篇关于如何从用C全系列int的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆