在Qt4中创建一个随机字符串或数字
是否有任何函数或类似的东西可以让我创建完全随机的字符串或数字?
Is there any function or something like that by which I can create totally random strings or numbers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用 qrand 创建随机数。如果需要字符串,可以将 int 转换为字符串。您还可以检查 QUuid 类,它生成通用唯一标识符。这些并不是“完全随机”的,但它们是独一无二的。
You can create random numbers using qrand. If you need strings, you can convert the int to string. You could also check the QUuid class, which generates Universally Unique Identifiers. Those are not 'totally random', but they are unique.
返回一个随机数
randomValue
,其中 0 <=randomValue
<数字
。qrand()
声明于QtGlobal 被许多其他 Qt 文件 #included。将整数转换为 QString。
returns a random number
randomValue
with 0 <=randomValue
<number
.qrand()
is declared in QtGlobal which is #included by many other Qt files.converts an integer to QString.
适用于 Qt6
生成从 0 到 10 的双精度数
Works in Qt6
Generate a double from 0 to 10
以下示例生成从 A 到 Z 的大写字母且长度 = len 的字母字符串。
The following example generates alphabetic strings with capital letters from A to Z and length = len.
这不是生成给定范围内的随机数的很好方法。 (事实上,这对于大多数生成器来说非常非常糟糕)
您假设生成器的低位是均匀分布的。大多数发电机的情况并非如此。在大多数生成器中,随机性发生在高阶位中。
通过使用除法后的余数,您实际上抛弃了随机性。
您应该使用乘法和除法进行缩放。不使用模运算符。
例如,
如果
generator_output
位于[0,generator_maximum]
中,my_number
将位于[start_required , start_required + range_required]
中。This is not a very good method to generate random numbers within a given range. (In fact it's very very bad for most generators )
You are assuming that the low-order bits from the generator are uniformly distributed. This is not the case with most generators. In most generators the randomness occurs in the high order bits.
By using the remainder after divisions you are in effect throwing out the randomness.
You should scale using multiplication and division. Not using the modulo operator.
eg
If
generator_output
is in[0, generator_maximum]
,my_number
will be in[start_required , start_required + range_required]
.使用QUuid
Use QUuid
这里是使用qrand()。下面的解决方案使用 QUuid,正如上面已经建议的那样,生成随机和唯一的 ID(它们都是
十六进制
数字):输出
Here is the good answer using qrand(). The solution below uses QUuid, as already was suggested above, to generate random and unique ids (they are all
hex
numbers):Output