#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int index = 0;
int inputCnt = 0;
char *cardColor[4] = {"黑桃","红桃","梅花","方片"};
int cardNum[13];
for(index=0; index<13; index++)
{
cardNum[index] = index+1;
}
printf("please input card num:");
while( scanf("%d", &inputCnt) != EOF)
{
printf("\n");
srand((int)time(0)); /*每次都 初始化随即数种子*/
for(index = 0; index<inputCnt; index++)
{
printf("%s", cardColor[rand()%4]);
printf("%d ",cardNum[rand()%13]);
}
printf("\n\n");
printf("please input card num:");
}
return 0;
}
-------------------以上代码有问题,忘记判断是否牌已经发过,修改后代码如下--------------------
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
static int checkCard(int cardCnt, int (*pInput)[2]);
int main()
{
int index = 0;
int inputCnt = 0;
int colorIndex = 0;
int numIndex = 0;
int selectedCard[52][2];
char *cardColor[4] = {"黑桃","红桃","梅花","方块"};
int cardNum[13];
for(index=0; index<13; index++)
{
cardNum[index] = index+1;
}
memset(&selectedCard[0][0], 0, sizeof(selectedCard));
#if 0 /*调式牌面值是否有重复的*/
for(index=0;index<4;index++)
for(inputCnt=0;inputCnt<13;inputCnt++)
{
printf("index=%d,inputCnt=%d, sum=%d \n",index,inputCnt,(index+1)*13+inputCnt+1);
}
#endif
printf("please input card num:");
while( scanf("%d", &inputCnt) != EOF)
{
if(inputCnt < 53)
{
printf("\n");
index = 0; /*已经找到符合要求的张数*/
srand((int)time(0));
while(index < inputCnt)
{
colorIndex = rand()%4;
numIndex = rand()%13;
selectedCard[index][1] = (colorIndex+1)*13 + numIndex + 1; /*记录下已经发出的牌,防止重复*/
//printf("--得到花色索引:%d,牌号索引:%d, 牌面值为:%d\n",colorIndex,numIndex,selectedCard[index][1]);
if(0 == checkCard(index, selectedCard))
{
printf("%s", cardColor[colorIndex]);
printf("%d ",cardNum[numIndex]);
index++;
}
else /*但发重复牌时需要清除刚才记录的牌面值*/
{
selectedCard[index][1] = 0;
}
}
printf("\n\n");
printf("please input card num:");
}
else
{
printf("输入的牌数超过52张,请重新输入!\n");
printf("please input card num:");
}
}
return 0;
}
/*检查当前生成的牌是否已经发过,0:没法过,1:发送过*/
static int checkCard(int cardCnt, int (*pInput)[2])
{
int index = 0;
int cnt = 0;
int ret = 0;
int errorFlag = 0;
#if 0 /*调试信息可以删除*/
printf("--cnt = %d,得到已经发过牌的号为:\r\n",cardCnt);
for(index=0; index<= cardCnt; index++)
{
printf("%d ", pInput[index][1]);
}
printf("\n");
printf("--比较过程如下:");
#endif
while(cnt < cardCnt)
{
for(index=cnt+1; index <= cardCnt; index++)
{
//printf("%d %d\n",pInput[cnt][1], pInput[index][1]);
if(pInput[cnt][1] == pInput[index][1])
{
errorFlag = 1;
//printf("--ERROR--得到重复的牌--\n");
break;
}
}
cnt = cnt + 1;
if(errorFlag == 1)
{
ret = 1;
break;
}
}
return ret;
}
追问请问char里面不应该是字符型吗 怎么可以是两个汉字呢?