这是我的ramdomize代码:
int monstername;
monstername = rand() % 3;
但是我想要0,70%的输出1和20%2,10%我怎么能用C做这个?
答案 0 :(得分:4)
int monstername;
int random_var = rand() % 10;
if(random_var < 7) {
// 0-70%
monstername = 0;
}
else if(random_var < 9) {
// 70-90% here
monstername = 1;
}
else {
// 90-100% here
monstername = 2;
}
答案 1 :(得分:3)
尝试
int monstername;
int rn = rand();
if (rn < 0.7*RAND_MAX)
monstername = 0;
else if (rn < 0.9*RAND_MAX)
monstername = 1;
else
monstername = 2;
答案 2 :(得分:2)
假设您不关心modulo bias,您需要以下内容:
int monstername;
int r = rand() % 10;
if (r < 7)
monstername = 0;
else if (r < 9)
monstername = 1;
else
monstername = 2;
如果您 关心模偏差,请查看arc4random_uniform(3)
而不是rand(3)
。
答案 3 :(得分:1)
int weighted[10] = {0,1,0,0,1,0,0,2,0,0};
monstername = weighted[rnd() % 10];