Rand () keeps returning 0

I am using Visual Studio 2010 and C programming. I am trying to create a random integer value through the rand () method. Here is the code:

/*main.cpp*/
int main (void)
{
    InitBuilding();

    return 0;
}

/*building.cpp*/
//includes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

//data structure
typedef struct
{
    int type;   //building type
} BUILDING;

//global variables
BUILDING g_aBld[200];

//initialization
void InitBuilding(void)
{
    srand((unsigned)time(NULL));

    for(int cntBld = 0; cntBld < 200; cntBld++)
    {  
         g_aBld[cntBld].type = (rand() % 3);
    }
}

After debugging, I realized that 0 is continuously generated for each iteration of the loop. I used this exact code before in other programs and it worked fine. I have no idea why this will not work now. Thanks in advance for any answers.

+4
source share
2 answers
     g_aBld[cntBld].type = (rand() % 3);

Do not use mod to reduce the range rand, because it can interact poorly with how your random number generator initializes. Try for example:

     g_aBld[cntBld].type = rand() / (RAND_MAX / 3);
+1
source

int main( int argc, char ** argv )
{
    InitBuilding();
}

, 0, 1, 2

+1

Source: https://habr.com/ru/post/1610238/


All Articles