gpt4 book ai didi

c++ - rand() 和 srand() 函数 opengl visual cpp

转载 作者:太空宇宙 更新时间:2023-11-04 15:25:02 26 4
gpt4 key购买 nike

我正在用 opengl 制作吃 bean 人游戏,我需要生成 2 个不同的数字 0 或 1,它们根据我的吃 bean 人所采取的方向对我的吃 bean 人的方向负责。

如何使用 rand() 函数生成一个数字,该函数为一个数字生成 75% 的随机性,为另一个数字生成 25% 的随机性?

如果我做:

n = rand() % 3;

它将得到 2 个不同的数字。问题是我不知道如何制作的随机百分比。我可以用一个 cicle 和一个柜台来制作它。但我被告知我可以直接在 rand() 函数中完成。我搜索但在谷歌上找不到任何具体内容。

最佳答案

使用 <random>图书馆。 bernoulli_distribution 将以给定的概率 p 生成 true,以概率 1-p 生成 false。

#include <random>

#include <iostream>
#include <algorithm>
#include <iterator>

int main() {
std::generate_n(std::ostream_iterator<bool>(std::cout," "), 10,
std::bind(std::bernoulli_distribution(0.25), std::mt19937()));
}

打印:

1 0 0 1 0 0 1 0 0 0 

关于c++ - rand() 和 srand() 函数 opengl visual cpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10463244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com