【发布时间】:2015-10-05 08:13:17
【问题描述】:
我正在使用 Visual Studio 2010 并使用 C 进行编程。我试图通过 rand() 方法生成一个随机整数值。代码如下:
/*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);
}
}
经过调试,我意识到循环的每次迭代都会不断生成 0。我之前在其他程序中使用过这个确切的代码,它工作得很好。我不知道为什么它现在不起作用。 提前感谢您的任何回复。
【问题讨论】:
-
请提供一个简短但完整的示例来演示该问题——我们可以编译并运行该示例以重现该问题。
-
@Thomas OP 没有将
srand()调用放入循环中。所以它不是重复的。 -
你能澄清一下是
rand()还是rand()%3给出的结果为0? -
@Thomas 这根本不是真的,
rand()不是基于时钟的。 -
您是如何确认的?这适用于我的编译测试
g_aBld。在优化构建中,这可能不会被视为填充数组