C++ random int function

9.2k views Asked by At

Hello dear members of stackoverflow I've recently started learning C++, today I wrote a little game but my random function doesn't work properly. When I call my random function more than once it doesn't re-generate a number instead, it prints the same number over and over again. How can I solve this problem without using for loop? Thanks

#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int rolld6();

int main()
{
    cout<<rolld6()<<endl;
    cout<<rolld6()<<endl;
    system("PAUSE");
    return 0;

}

int rolld6()
{
    srand(time(NULL));
    return rand() % 6 + 1;;
}
3

There are 3 answers

0
paxdiablo On BEST ANSWER

srand(time(NULL)); should usually be done once at the start of main() and never again.

The way you have it will give you the same number every time you call rolld6 in the same second, which could be a lot of times and, in your sample, is near guaranteed since you call it twice in quick succession.

Try this:

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

int rolld6 (void) {
    return rand() % 6 + 1;
}

int main (void) {
    srand (time (NULL));
    std::cout << rolld6() << std::endl;
    std::cout << rolld6() << std::endl;
    system ("PAUSE");
    return 0;
}

One other thing to keep in mind is if you run this program itself twice in quick succession. If the time hasn't changed, you'll get the same two numbers in both runs. That's only usually a problem when you have a script running the program multiple times and the program itself is short lived.

For example, if you took out your system() call and had a cmd.exe script which called it thrice, you might see something like:

1
5
1
5
1
5

It's not something you usually do but it should be kept in mind on the off chance that the scenario pops up.

0
GWW On

You are constantly reseeding the random number generator. Only call srand(time(NULL)); once at the beginning of your program.

1
Jason Rogers On

Random functions (no matter the language) are only partially random.

in every technology you will have a equivalent to

srand(time(NULL));

This piece of codes seeds the random function to a start value and then the numbers a generated from there onwards this means if your always reseeding form the same value you'll always get the same numbers

In your case you want to do something like this (calling srand(time(NULL)); only once).

int rolld6 (void) {
    return rand() % 6 + 1;;
}

int main (void) {
    srand (time (NULL));
...
//call your function here
}

one of the advantage of seeding with the same value is to offer the possibility to regenerate the same sequence of random numbers.

in one of my games, I would randomly place objects on the screen, but I also wanted to implement a retry option. this options of reseeding from the same value allows me to redo it without storing all the random values ^^