简体   繁体   English

如何在C中从2中分配某物?

[英]How to pick assign something to something out of 2 in C?

so i have got a struct that goes: 所以我有一个结构去:

enum input_result get_human_player(struct player* human)
{
    char playerName[NAMELEN];
    printf("What is your name? ");
    fgets(playerName, NAMELEN, stdin);
    strcpy((*human).name, playerName);

    (*human).type = HUMAN;
    (*human).thiscolor = C_WHITE;
    (*human).counters = 0;

    return FAILURE;
}

how do i make it so it randomly assigns it to either C_WHITE or C_RED with a 50/50 chance? 我如何使它以50/50的机会随机分配给C_WHITE或C_RED?

rand will return a random integer. rand将返回一个随机整数。 Assuming it is uniformly distributed (which might not be true, as not guaranteed by every implementation), the number will be odd or even with 50/50 chance. 假设它是均匀分布的(这可能不是真的,因为每个实现都无法保证),那么这个数字将是奇数,甚至是50/50的机会。 Using this fact: 利用这个事实:

if (rand() % 2)
{
    //Do the first thing
}
else
{
    // Do the other one
}

** Don't forget to seed the random number generator. **不要忘记为随机数生成器植入种子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM