小甲鱼作业中一疑问
这是S1E31https://fishc.com.cn/forum.php?mod=viewthread&tid=77858&extra=page%3D1%26filter%3Dtypeid%26typeid%3D570动手的一道题。我还是没明白洗牌代码的妙处,没看懂{:10_266:} ,请教各位!!!可不可以再详细地讲解一下。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shuffle(int array[], int length);
void deal(int array[], int player);
void show(char names, int player);
void shuffle(int array[], int length)
{
int index, temp, i;
srand(time(NULL));
for (i = 0; i < length; i++)
{
index = rand() % (length - i) + i;
if (index != i)
{
temp = array;
array = array;
array = temp;
}
}
}
void deal(int array[], int player)
{
int i, j, k = 0;
// 模拟发牌:拿起一副无序的扑克每人轮流发一张牌
for (i = 0; i < 14; i++)
{
for (j = 0; j < 3; j++)
{
player = array;
}
}
}
void show(char names, int player)
{
int i, j, poker;
printf("\n方=方角,梅=梅花,红=红桃,黑=黑桃\n\n");
for (i = 0; i < 3; i++)
{
printf("%s手上的牌是:", names);
for (j = 0; j < 14; j++)
{
poker = player;
if (poker < 11 && 0 < poker)
{
printf("方%d ", poker);
}
else if (poker < 21 && 10 < poker)
{
printf("梅%d ", poker-10);
}
else if (poker < 31 && 20 < poker)
{
printf("红%d ", poker-20);
}
else if (poker < 41 && 30 < poker)
{
printf("黑%d ", poker-30);
}
else
{
switch (poker)
{
case 41: printf("方J "); break;
case 42: printf("方Q "); break;
case 43: printf("方K "); break;
case 44: printf("梅J "); break;
case 45: printf("梅Q "); break;
case 46: printf("梅K "); break;
case 47: printf("红J "); break;
case 48: printf("红Q "); break;
case 49: printf("红K "); break;
case 50: printf("黑J "); break;
case 51: printf("黑Q "); break;
case 52: printf("黑K "); break;
case 53: printf("小王 "); break;
case 54: printf("大王 "); break;
}
}
}
printf("\n\n");
}
}
int main(void)
{
int array;
int player;
int i, ch;
char names;
// 初始化扑克牌
// 1~10代表方(角)1~10, 41、42、43代表方(角)J、Q、K
// 11~20代表梅(花)1~10, 44、45、46代表梅(花)J、Q、K
// 21~30代表红(桃)1~10, 47、48、49代表红(桃)J、Q、K
// 31~40代表黑(桃)1~10, 50、51、52代表黑(桃)J、Q、K
// 53、54当然就代表小王大王啦~
for (i = 0; i < 54; i++)
{
array = i + 1;
}
for (i = 0; i < 3; i++)
{
printf("\n请输入%d号玩家的名字:", i+1);
scanf("%s", names);
}
do
{
shuffle(array, 54);
deal(array, player);
show(names, player);
printf("重新洗牌(Y/N)?");
do
{
ch = getchar(); // 过滤输入缓冲区的其他字符
} while (ch != 'Y' && ch != 'N');
} while (ch == 'Y');
return 0;
} 本帖最后由 jhq999 于 2022-12-20 23:44 编辑
void shuffle(int array[], int length)
{
int index, temp, i;
srand(time(NULL));
for (i = 0; i < length; i++)
{
index = rand() % (length - i) + i;//i从0开始,在i到length-1之间选一张不是i的牌和i对换,是i不动
//这时候i的牌已经选好,i加一,接着在i+1和length-1再选,这样循环迭代,直到最后length - i=1时不动
if (index != i)
{
temp = array;
array = array;
array = temp;
}
}
} jhq999 发表于 2022-12-20 21:17
赞同
页:
[1]