在C ++中使用rand()函数的正确方法是什么? [英] What's the Right Way to use the rand() Function in C++?

查看:402
本文介绍了在C ++中使用rand()函数的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个书练习,说写一个产生伪随机数的程序。我从简单的开始。

  #includestd_lib_facilities.h

int randint b $ b {
int random = 0;
random = rand();
return random;
}

int main()
{
char input = 0;
cout<< 按任意字符并输入以生成一个随机数。 << endl;
while(cin>> input)
cout<< randint()<< endl;
keep_window_open();
}



我注意到每次运行程序时,随机输出。因此,我研究了随机数生成器,并决定通过在randint()中包含这种方法来尝试播种。

  srand(5355) 

这些只是生成了相同的数字(我现在觉得很愚蠢。 p>

所以我以为我会聪明,并像这样实现种子。

   

这基本上只是和程序一样,但输出了不同的数字(这是有意义的,因为由rand()生成的第一个数字总是41.)



我想到的唯一的事情是使它更随机: p>


  1. 让用户输入一个数字并将其设置为种子(这很容易实现,但这是最后的办法)
    OR

  2. 不知何故,将种子设置为计算机时钟或其他不断变化的数字。

我在头上,我应该停止吗?选项2难以实现?任何其他想法?



提前感谢。

解决方案

不难,这里你去:

  srand(time(NULL)); 

您需要包含 stdlib.h srand() time.h c>。


I'm doing a book exercise that says to write a program that generates psuedorandom numbers. I started off simple with.

#include "std_lib_facilities.h"

int randint()
{
    int random = 0;
    random = rand();
    return random;
}

int main()
{
    char input = 0;
    cout << "Press any character and enter to generate a random number." << endl;
    while (cin >> input)
    cout << randint() << endl;
    keep_window_open();
}

I noticed that each time the program was run, there would be the same "random" output. So I looked into random number generators and decided to try seeding by including this first in randint().

    srand(5355);

Which just generated the same number over and over (I feel stupid now for implementing it.)

So I thought I'd be clever and implement the seed like this.

srand(rand());

This basically just did the same as the program did in the first place but outputted a different set of numbers (which makes sense since the first number generated by rand() is always 41.)

The only thing I could think of to make this more random is to:

  1. Have the user input a number and set that as the seed (which would be easy to implement, but this is a last resort) OR
  2. Somehow have the seed be set to the computer clock or some other constantly changing number.

Am I in over my head and should I stop now? Is option 2 difficult to implement? Any other ideas?

Thanks in advance.

解决方案

Option 2 isn't difficult, here you go:

srand(time(NULL));

you'll need to include stdlib.h for srand() and time.h for time().

这篇关于在C ++中使用rand()函数的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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