我正在创建一个二十一点计划。我希望随机发牌。如果我使用 rand() 函数并将 srand() 初始化为 time(NULL),那么所有的卡片都是一样的。知道问题可能是什么吗?
//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>
#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;
}