我刚刚开始使用 C++,正在创建一个简单的基于文本的冒险。我试图弄清楚如何进行基于概率的事件。例如,当你打开盒子时,有 50% 的可能性是一把剑,有 50% 的可能性是一把刀。我知道如何制作随机数生成器,但我不知道如何将该数字与某些东西关联起来。我创建了我想要的变体,但它要求用户输入随机数。我想知道如何根据随机数是否大于或小于 50 来判断 if 语句,而不是根据用户输入的数字大于或小于 50 来判断。
将其余运算符 % 与 rand 一起使用。 rand()%2 可以给你 0 或 1。 让 0 成为一把剑,1 成为一把刀。
如果你还需要一把斧头,那么使用 rand()%3。
它可以给你 0,1 或 2。
2 代表轴,0 和 1 与上面一样。
那么 if 和 else 就很明显了。
rand()%n 其中 n 是一个大数,有更高的概率给出较小的数字。概率分布不均匀。您可以查看 stl 或 boost 的一些随机数生成器。
你说的是基于概率的事件,所以我会用随机项目来解释。
#include <iostream>
#include <random>
int main(){
//you create an array or another similar data structure, that has an index
//each index will respond to an event/item/anything really
std::string event[5]={"axe","sword","knive","bow","nothing"};
//now you create the index for the array to return the item
//we will be using the rand function for this
//the % operator returns the rest from a division with 5
int index = rand()%5;
//since an array starts from 0 and & returns 0-4, we can just plop index into event
std::cout<<"you get a "<<event[index];
}
rand()
,它会生成 0..RAND_MAX
范围内的数字。因此,对于 50% 的概率,您可以执行以下操作:
#include <stdlib.h>
if (rand() < RAND_MAX / 2)
{
// sword - 50% probability
}
else
{
// knife - 50% probability
}
您显然可以将其扩展到两种以上不同的情况,每种情况具有任何给定的概率,只需为每种情况在
0..RAND_MAX
范围内定义适当的阈值,例如
int r = rand();
if (r < RAND_MAX / 4)
{
// sword - 25% probability
}
else if (r < 3 * RAND_MAX / 4)
{
// knife - 50% probability
}
else
{
// axe - 25% probability
}