4

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?

4

4 回答 4

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;
}
于 2013-11-06T22:57:24.187 回答
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;
于 2013-11-06T23:01:04.267 回答
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).

于 2013-11-06T22:58:01.093 回答
1
int weighted[10] = {0,1,0,0,1,0,0,2,0,0};
monstername = weighted[rnd() % 10];
于 2013-11-06T23:06:50.903 回答