Random Numbers in C++
I'm creating a BlackJack Program. I want the cards to be randomly dealt. if i use the rand() function and initialize srand() to time(NULL) then all the cards turn out to be same. Any idea what the problem might be ?
//Cards.h
#include <iostream>
#include <time.h>
#include <cstdlib>
using namespace std;
class Cards
{
private:
int val_seed,suit_seed;
public:
int val[10];
string card[10];
int dealcard(int x)
{
srand();
val_seed=rand()%13 + 2;
suit_seed=rand()%4 + 1;
if(val_seed>=1 && val_seed<=10)
{
if(val_seed==10)
{
card[x]="10";
}
else
{
card[x]=val_seed+48;
}
}
else if(val_seed>10)
{
switch(val_seed)
{
case 11: card[x]="J"; val_seed=10; break;
case 12: card[x]="Q"; val_seed=10; break;
case 13: card[x]="K"; val_seed=10; break;
case 14: card[x]="A"; val_seed=11; break;
}
}
switch(suit_seed)
{
case 1: card[x]+='\3'; break;
case 2: card[x]+='\4'; break;
case 3: card[x]+='\5'; break;
case 4: card[x]+='\6'; break;
}
val[x]=val_seed;
}
};
//main.cpp
#include <cstdlib&开发者_如何学编程gt;
#include <iostream>
#include "Cards.h"
using namespace std;
int main(int argc, char *argv[])
{
Cards k;
for(int a=1; a<=9; a++)
{
k.dealcard(a);
}
for(int e=1; e<=9; e++)
{
cout<<k.card[e]<<"("<<k.val[e]<<")"<<" ";
}
cout<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Seed the number generator ONCE. If you run your function in a loop they will be executed faster than the time resolution interval (so all the seeds are the same and therefore the numbers).
While developing the app and debugging it it will help if you seed the generator with the same, known value. This means successive debugging sessions will use the same values from the generator. Don't forget to switch back to a time() based seed in your release build (or use the pre-processor to detect if it's a Debug or Release build and do it for you).
See http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
srand is best initialised with a unique value, eg, the time, as computers dont generate random numbers but in effect work from a predone list, this sets the start point to be less determinable.
You do not want to call srand
every time you use rand
, just call it once at the start of the program and you will be fine.
Calling it with the time as parameter will also make sure you will get a different random sequence each time you run the program.
Problems using srand()
notwithstanding, your card generation algorithm is wrong. Even the possibility of it generating two of the same card in a row means it is wrong.
You should take a deck of cards (52 or some multiple thereof), shuffle it using a randomly generated seed, and deal cards from the shuffled deck.
You are seeding srand()
with null; seed with current clock time and then retry it should solve your problem.
time_t now;
time(&now);
srand((unsigned int)now);
精彩评论