Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Right Way to use the rand() Function in C++?

Tags:

c++

random

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.

like image 258
trikker Avatar asked Jul 13 '09 00:07

trikker


People also ask

Why do we use rand in C?

The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767.

Does rand () generate 0?

rand produces numbers from the open interval (0,1) , which does not include 0 or 1, so you should never get those values..

Where is the function rand mostly used for?

As a financial analyst, the RAND function can be used to generate random numbers. However, it is used less frequently in the finance industry, as compared to other fields such as cryptography and statistics.


1 Answers

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

like image 99
John T Avatar answered Sep 19 '22 01:09

John T