C ++中的rand()和srand() [英] rand() and srand() in C++

查看:114
本文介绍了C ++中的rand()和srand()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背后是否有逻辑或原则?

Is there some logic or principle behind that?

生成的数字是完全随机的吗?

Are the numbers generated completely random?

假设我正在运行此程序:

Suppose I am running this program:

#include <iostream.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    /*
    Declare variable to hold seconds on clock.
    */
    time_t seconds;
    /*
    Get value from system clock and
    place in seconds variable.
    */
    time(&seconds);
    /*
    Convert seconds to a unsigned
    integer.
    */
    srand((unsigned int) seconds);
    /*
    Output random values.
    */
    cout<< rand() << endl;
    cout<< rand() << endl;
    cout<< rand() << endl;
    return 0;
}

显示内容: http://img14.imageshack.us/img14/1538/98271820.png

显示两次205.

推荐答案

从第二个问题开始:

生成的数字是完全随机的吗?

Are the numbers generated completely random?

不,这在计算机中极不可能发生.它们是伪随机"数字,它是一些数字序列,其范围随时间以类似随机的方式变化.但是,如果您从相同的种子"开始,则每次都会获得相同的序列.这种可预测性有时非常有用,因为它允许以相同的结果重复几次相同的实验-更改种子,将使相似的运行具有不同的结果.

No, that is very unlikely to ever happen in a computer. They are "pseudo-random" numbers, which is some sequence of numbers that vary in range over time in a random-like fashion. But if you start with the same "seed", you get the same sequence each time. This predictability is sometimes very useful, as it allows repeating the same experiment several times with the same outcome - altering the seed, will allow a similar run to have a different outcome.

函数srand设置种子.某些系统确实具有称为randomize的功能,但它本身并不是标准的一部分.如果确实存在,则会将种子设置为代码未知的内容-例如当前时间(以毫秒为单位).

The function srand sets the seed. Some systems do have a function called randomize, but it is not part of the standard as such. If it does exist it sets the seed to something unknown to the code - such as the current time in milliseconds.

其背后是否有逻辑或原则?

Is there some logic or principle behind that?

是的.有几种生成伪随机数的方法.简单的变量可以使用常规的intlong类型用一两行C代码编写,仅包括将当前值" +一些常数乘以一个大数,然后对另一个大数取模.

Yes. There are several methods for generating pseudo-randum numbers. Simple ones can be written in one or two lines of C code using regular int or long types, and just consists of taking the "current value" + some constant, multiplied by some large number and modulo some other large number.

更复杂的运算涉及数十行相当复杂的数学运算,这些运算具有大量数字-例如,梅森·Twister(Mersenne Twister)是最近的著作,如果您稍作搜索,就可以将其作为源代码使用.

More complex ones involve dozens of more lines of rather complicated math with large numbers - for example Mersenne Twister is a recent work that is available as source code if you search a little bit.

这篇关于C ++中的rand()和srand()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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