随机ABCD Char Generator
我正在制作测验游戏,并且在玩家打电话给他的朋友(这是一个简单的代表)时,该程序会打印出一个随机的Answe(A,B,C或D)的随机字符,并且一个随机的数字可以显示他是多么确定他是(从1到100)。无论如何,我在控制台中尝试char始终是D,而且数字总是87。我不知道如何做这项工作。这是当前的代码:
char x = *("ABCD" + rand() % 4);
int y = 1+ (rand() % 100);
I am making a quiz game and want when the player calls his friend(which is a simple cout), the program prints a random char of an answe(A, B, C or D) and a random number to present how sure he is(from 1 to 100). Whetever I try the char in console is always D, and the number is always 87. I don't know how to make this work. This is the current code:
char x = *("ABCD" + rand() % 4);
int y = 1+ (rand() % 100);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
随机数的生成并不像您想象的那样简单。
请参阅此处的一些一般信息:随机数 - wikipedia 。
为了使用
rand 您应该初始化随机种子(请参阅链接)。
建议使用当前时间作为种子来获取“良好”随机值。请注意,使用
srand
设置种子仅应调用一次。在下面,您可以看到代码的固定版本,该版本在每次运行中产生不同的值:
- 由于C ++ 11标准库对随机生成器具有良好的现代支持。请参阅: pseudo-random编号生成。
它需要更多的样板,但是您可以更好地控制随机值的产生。在
rand()
在您的情况下的一个很好的替代方法是std :: Surifter_int_distribution
。以下是一些信息,为什么为什么比旧的
rand()
:使用Uniform_int_distribution与模量操作的优点是什么?。下面的代码显示了如何在您的情况下使用它(
rd
的发起,gen
,distrib1
,distrib2 应该只做一次):
Random numbers generation is not as simple as you might think.
See here some general info: Random number generation - Wikipedia.
In order to use
rand
properly, you should initialize the random seed (see the link).Using the current time as seed is recommended for getting "nice" random values. Note that setting the seed using
srand
should be called only once.Below you can see a fixed version for your code, that produce different values (potentially) in each run:
However - since C++11 the standard library has good and modern support for random generators. See: Pseudo-random number generation.
It requires a bit more boilerplate, but you have better control over the generation of random values. See more info in the
<random>
header, which contains a lot of classes and utilities.A good alternative to
rand()
in your case is thestd::uniform_int_distribution
.Here is some info why to prefer it over the old
rand()
: What are the advantages of using uniform_int_distribution vs a modulus operation?.The code below shows how to use it in your case (the initilization of
rd
,gen
,distrib1
,distrib2
should be done only once):