cocos2dx-3.x提供了一个用于生成 【0,1)之间浮点数的宏定义 CCRANDOM_0_1
1. 宏定义说明
首先查看源码,定位分析:
1
2
3
4
|
/**
@def CCRANDOM_0_1 returns
a random float between 0 and 1 */ #define
CCRANDOM_0_1() cocos2d::rand_0_1() |
cocos2d::rand_0_1()函数的原型为:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** *
Returns a random float between 0 and 1. *
It can be seeded using std::srand(seed); */ inline float rand_0_1()
{ //
FIXME: using the new c++11 random engine generator //
without a proper way to set a seed is not useful. //
Resorting to the old random method since it can //
be seeded using std::srand() return std:: rand ()
/ ( float )RAND_MAX; //
return cocos2d::random(0.f, 1.f); }; |
从上面的源码可以看出,CCRANDOM_0_1()其实就是调用标准库函数 rand(),随机生成0 - 1,左开右闭区间内的浮点数
2. rand函数
标准库函数生成随机数,采用的是rand函数,生成一个【0, RAND_MAX】 之间的整数,常用的实例如:
1
2
3
4
5
6
7
8
9
|
#include
<time.h> #include
<stdlib.h> int main() { srand ((unsigned int ) time (0));
// 设置随机数种子 printf ( "%d\n" , rand ()); return 0; } |
3. CCRANDOM_0_1使用
在具体的使用过程中,需要注意两点
1. 初始化随机数种子
2. 注意闭合区间,尤其是生成随机整数时,更需要确保闭合区间,圆括号的使用----> 查看下例中第十行
一个使用例子,用于随机生成0,1两个整数: (int)(CCRANDOM_0_1() * 2)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include
"cocos2d.h" int test() { struct timeval
now; gettimeofday(&now,
NULL); //
linux 下获取当前时间,精确到微妙 srand ((unsigned int )(now.tv_sec*1000
+ now.tv_usec/1000)); //
set random seed //
generate random o or 1 int value
= ( int )
(CCRANDOM_0_1() * 2); log ( "value
is %d\n" ,
value); return value; } |