首先,一副牌有54张,可以与0~53一一对应,所以定义一个数组,用0~53来表示这副牌。洗牌的过程就相当于数组中的元素随机的进行交换。
对这54个数,每一个对应的生成一个随机数,然后将当前位置上的数与生成的随机位置上的进行交换就可以了。
这样可以随意洗牌了。
#include<stdio.h> #include<stdlib.h> void shuffle(int *poker) { int temp; int r; for(int i = 0; i < 54; ++i) { //产生一个0~53的随机数 r = rand()%54; temp = poker[i]; poker[i] = poker[r]; poker[r] = temp; } } void main() { int poker[54]; int i; char ch= 'y'; for(i = 0; i < 54; ++i) { poker[i] = i; printf("%d ",i); } while (ch != 'n' && ch != 'N') { shuffle(poker); printf("\n洗牌之后:\n"); for(i = 0; i < 54; ++i) printf("%d ",poker[i]); printf("\n按n退出,按任意键继续:"); ch = getchar(); getchar(); } }