简体   繁体   English

rand()一直返回0

[英]rand() keeps returning 0

I am using Visual Studio 2010 and programming in C. I am attempting to produce a random integer value via the rand() method. 我正在使用Visual Studio 2010并在C中编程。我试图通过rand()方法生成随机整数值。 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've realized that 0 is continually generated for each iteration of the loop. 在调试之后,我意识到循环的每次迭代都会连续生成0。 I've used this exact code before in other programs, and it worked fine. 我之前在其他程序中使用过这个确切的代码,并且工作正常。 I have no idea why it wouldn't be working now. 我不知道为什么现在不行。 Thanks in advance for any replies. 提前感谢您的回复。

     g_aBld[cntBld].type = (rand() % 3);

Don't use mod to reduce the range of rand because this can interoperate badly with the way your random number generator initializes itself. 不要使用mod来减少rand的范围,因为这可以与随机数生成器初始化自身的方式非常互操作。 Try, for example: 试试,例如:

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

Project compiled with the addition of 项目编译加上

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

With this added the code worked producing types of 0, 1, 2 通过添加,代码可以生成0,1,2的类型

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

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