C语言 c - 随机数生成器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2396578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:45:25  来源:igfitidea点击:

c - random number generator

crandom

提问by tm1

How do I generate a random number between 0 and 1?

如何生成一个介于 0 和 1 之间的随机数?

回答by Mark Elliot

You can generate a pseudorandom number using stdlib.h. Simply include stdlib, then call

您可以使用stdlib.h生成伪随机数。只需包含 stdlib,然后调用

double random_number = rand() / (double)RAND_MAX;

回答by qrdl

Assuming OP wants either 0 or 1:

假设 OP 想要 0 或 1:

srand(time(NULL));
foo = rand() & 1;

Edit inspired by comment: Old rand()implementations had a flaw - lower-order bits had much shorter periods than higher-order bits so use of low-order bit for such implementations isn't good. If you know your rand()implementation suffers from this flaw, use high-order bit, like this:

受评论启发进行编辑:旧rand()实现有一个缺陷 - 低位的周期比高位短得多,因此在此类实现中使用低位并不好。如果您知道您的rand()实现存在此缺陷,请使用高位,如下所示:

foo = rand() >> (sizeof(int)*8-1)

assuming regular 8-bits-per-byte architectures

假设常规的每字节 8 位架构

回答by ephemient

man 3 drand48is exactlywhat you asked for.

男子3 drand48正是你问什么。

The drand48()and erand48()functions return non-negative, double-precision, floating-point values, uniformly distributed over the interval [0.0 , 1.0].

所述drand48()erand48()函数返回非负,双精度浮点值,均匀地分布在区间[0.0,1.0]分布。

These are found in #include <stdlib.h>on UNIX platforms. They're not in ANSI C, though, so (for example) you won't find them on Windows unless you bring your own implementation (e.g. LibGW32C).

这些可以在#include <stdlib.h>UNIX 平台上找到。但是,它们不在 ANSI C 中,因此(例如)除非您带来自己的实现(例如LibGW32C),否则您不会在 Windows 上找到它们。