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;;
}
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.