C ++如何获取1到12之间的随机值? [英] C++ How I can get random value from 1 to 12?

查看:259
本文介绍了C ++如何获取1到12之间的随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得1到12之间的C ++随机值?

How I can get in C++ random value from 1 to 12?

那么我将有3个,6个或11个?

So I will have 3, or 6, or 11?

推荐答案

使用以下公式:

M + rand() / (RAND_MAX / (N - M + 1) + 1), M = 1, N = 12

并阅读此常见问题解答.

关于此问题的大多数答案都没有考虑到不良的PRN生成器(通常随库函数rand()提供)在低阶位不是很随机的事实.因此:

Most answers on this question do not take into account the fact that poor PRN generators (typically offered with the library function rand()) are not very random in the low order bits. Hence:

rand() % 12 + 1

不够好.

这篇关于C ++如何获取1到12之间的随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆