如何在C ++中生成一个随机数? [英] How to generate a random number in C++?

查看:292
本文介绍了如何在C ++中生成一个随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用骰子做一个游戏,我需要有随机数字(模拟模具的两边,我知道如何使它在1和6之间)。使用

I'm trying to make a game with dice, and I need to have random numbers in it (to simulate the sides of the die. I know how to make it between 1 and 6). Using

#include <cstdlib> 
#include <ctime> 
#include <iostream>

using namespace std;

int main() 
{ 
    srand((unsigned)time(0)); 
    int i;
    i = (rand()%6)+1; 
    cout << i << "\n"; 
}

无法正常工作,因为当我运行程序几次,这里是我得到的输出:

doesn't work very well, because when I run the program a few times, here's the output I get:

6
1
1
1
1
1
2
2
2
2
5
2

所以我想要一个命令,每次生成一个不同的随机数,而不是连续5次的同一个。是否有一个命令会这样做?

So I want a command that will generate a different random number each time, not the same one 5 times in a row. Is there a command that will do this?

推荐答案

测试应用程序最基本的问题是你调用 srand 一次,然后调用 rand 一次并退出。

The most fundamental problem of your test application is that you call srand once and then call rand one time and exit.

srand 函数是用随机种子初始化伪随机数序列。这意味着如果你在两个不同的应用程序中传递相同的值到 srand (与 srand / rand 实现),你会得到完全相同的序列 rand()之后读取的值。但是你的伪随机序列只包含一个元素 - 你的输出包括不同的伪随机序列的第一个元素,种子具有1秒精度的时间。那么你期望看到什么?当你碰巧在同一秒钟运行应用程序时,你的结果当然是一样的(正如Loki Astari在对答案的评论中已经提到的那样)。

The whole point of srand function is to initialize the sequence of pseudo-random numbers with a random seed. It means that if you pass the same value to srand in two different applications (with the same srand/rand implementation) you will get exactly the same sequence of rand() values read after that. But your pseudo-random sequence consists of one element only - your output consists of the first elements of different pseudo-random sequences seeded with time of 1 second precision. So what do you expect to see? When you happen to run application on the same second your result is the same of course (as Loki Astari already mentioned in a comment to the answer).

其实你应该调用 srand(seed)一次,然后调用 rand()多次,并分析该序列 - 它应该看起来随机。

Actually you should call srand(seed) one time and then call rand() many times and analyze that sequence - it should look random.

这篇关于如何在C ++中生成一个随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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