原创 QT 5.15.0 中 Qrand 函数更换为 QRandomGenerator 的问题处理
张浩
Bullzhanghao@163.com
在 QT 5.15.0 手册中,qrand 的描述如下:
int qrand()
This function is obsolete. It is provided to keep old source code working. We strongly
advise against using it in new code.
Thread-safe version of the standard C++ rand() function.
Returns a value between 0 and RAND_MAX (defined in <cstdlib> and <stdlib.h>), the next
number in the current sequence of pseudo-random integers.
Use qsrand() to initialize the pseudo-random number generator with a seed value. Seeding
must be performed at least once on each thread. If that step is skipped, then the sequence will be
pre-seeded with a constant value.
Note: This function is deprecated. In new applications, use QRandomGenerator instead.
This function was introduced in Qt 4.2.
手册告知我们,此 qrand 函数已经被 Qt 新版本抑制,建议不要使用,应使用
QRandomGenerator 替代,问题是应用时,需要设置随机数的范围,因此需要搞清楚 qrand
的随机数范围,查询 stdlib.h 文件,在 stdlib.h 中,RAND_MAX 定义为:
#define RAND_MAX 0x7fff
十六进制 0x7fff 转换为十进制为 32767,因为 qrand()的随机数的范围为 0-32767。
这样,可以把 qrand()函数替换为 QRandomGenerator::global()->bounded(0,32767)
问题解决。