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;;
}
You are constantly reseeding the random number generator. Only call
srand(time(NULL));
once at the beginning of your program.Random functions (no matter the language) are only partially random.
in every technology you will have a equivalent to
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).
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 ^^
srand(time(NULL));
should usually be done once at the start ofmain()
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:
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 acmd.exe
script which called it thrice, you might see something like:It's not something you usually do but it should be kept in mind on the off chance that the scenario pops up.