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 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.
You are constantly reseeding the random number generator. Only call srand(time(NULL));
once at the beginning of your program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With