c - 返回随机值 1 或 0 的函数

标签 c

<分区>

int random_var(void);

int main(void)
{
    int i;
    for (i = 1; i <= 50; i++)
        printf("%d\n", random_var());

return 0;
}


int random_var(void)
{
    srand((unsigned) time(NULL));
    return rand() % 2;
}

我的任务是编写一个函数,每次调用时返回随机值 1 或 0。即使我使用随机生成器作为种子,我的代码仍然返回一个固定值,为什么??

最佳答案

您只需调用一次srand()!

int random_var(void);

int main(void)
{
    int i;
    srand((unsigned) time(NULL));
    for (i = 1; i <= 50; i++)
        printf("%d\n", random_var());

    return 0;
}


int random_var(void)
{
    return rand() % 2;
}

或者(或另外),正如 Keith Thompson 指出的那样,您可以尝试采用更高阶的位,这可能会更好地分布。

关于c - 返回随机值 1 或 0 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40249525/

相关文章:

C - 打印特定图案

c11 _Generic 添加类型

c - 用 C 语言完成的 IDT 不起作用

python - 在 C 中使用 Python

c - 这个程序最后是怎么得到5的呢?

c - 你如何在 C 中声明字符串常量?

c - 需要一个通用库,纯 C

c - 宏扩展 : should it work? 后重新扫描 'defined' 运算符

java - 对 C/C++ 对象和 C/C++ 对象对 Java/Objective C 的 JSON 响应

无法使用 sscanf 获取值