在C中生成随机布尔的简单方法是什么? [英] What's a simple way to generate a random bool in C?

查看:86
本文介绍了在C中生成随机布尔的简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个用于游戏的随机布尔值,因此它不需要是密码安全的.我将在代码中使用stdbool.h,并且我也已经完成了#include <stdlib.h>.最好是,它应该非常快(因为我会生成很多),并且应该能够在C89中完成(只是偏爱).我对用C ++做到这一点完全不感兴趣.

I want to generate a random boolean for use in a game, so it does not need to be cryptographically secure. I will use stdbool.h in my code, and I have also done #include <stdlib.h>. Preferably, it should be very fast (as I will be generating many of them), and it should be able to be done in C89 (just preference). I am not interested at all in doing this in C++.

以下是我提出的一些方法:

Here are some of the ways I've come up with:

  • 从/dev/urandom中读取,过滤掉一位数字,并且> 5 =真,< 5 =假.
  • 继续调用rand()并过滤出低/高值.

推荐答案

只需调用rand()并获取其返回值的LSB.

Just call rand() and get the LSB of its return value.

bool randbool = rand() & 1;

请记住一开始要呼叫srand().

这篇关于在C中生成随机布尔的简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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