Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

random - What's the Right Way to use the rand() Function in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...