Here's my ramdomize code:
int monstername;
monstername = rand() % 3;
but I want 0 with 70% of output 1 with 20% 2 with 10% how I can do this with C?
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;
}
尝试
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;
假设你不关心模偏差,你想要这样的东西:
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)
.
int weighted[10] = {0,1,0,0,1,0,0,2,0,0};
monstername = weighted[rnd() % 10];