Reputation: 407
i had the following problem in my book:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
randomize();
int Game[]={10,16},P;
int Turn=random(2)+5;
for(int T=0;T<20;T++)
{
P=random(2);
cout<<Game[P]+Turn<<"#";
}
getch();
}
The output comes like 16#22#16#16#16#22#....20 times... Why the output of this always comes either 16# or 22#?? why not 15# or 21#?? i would like to the mechanism of this program. Thanks. turn=random(2)+5; if random(2) gives 0 then turn becomes turn=0+5=5 which implies that i should get 10+5=15 and 16+5=21 along with 16 and 22 but i m not getting them.
We got the above question in our computer science theory exam and we were to chose the correct answer(i.e it generates 16 and 22) but how will i am going to know that it will generate only 16 and 22. As i explained above 15 and 21 are also possible..
Upvotes: 0
Views: 530
Reputation: 1825
A computer cannot randomize numbers by itself, it uses a seed for that.
But seed's aren't completely random they just have a specific order, like:
1
2
8
5
4
These numbers look pretty random but when you run the program the next time you will get:
1
2
8
5
4
The exact same.
To prevent this we use the time as a seed, time always changes so it will always generate new numbers.
#include <time.h>
srand(time(NULL)); // srand is the function to randomize numbers from a seed, we use 'time' as seed here
this video explains it.
Upvotes: 1
Reputation: 6092
Because Turn
is only randomized once - at the beginning of the loop. If you move the assignment of Turn
into your loop, you should get 15
and 21
also:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
randomize();
int Game[]={10,16},P;
int Turn;
for(int T=0;T<20;T++)
{
P=random(2);
Turn=random(2)+5;
cout<<Game[P]+Turn<<"#";
}
getch();
}
Also, as said by others, if you want the output to differ between runs, you will need to seed your random number generator, for instance by calling srand()
with a seed. For instance:
#include <time.h>
(...)
srand(time(NULL));
Upvotes: 0
Reputation: 918
You need to give a seed
value that would help get "really" random. mumbers
Upvotes: 1
Reputation: 294
maybe this helps:
The seed for the random number generator is not set.
If you call srand(time(NULL)) then you will get more random results
C++ rand() gives same number when running process
Upvotes: 1