用C语言写一个简单的洗牌程序
时间: 2023-12-03 15:03:30 浏览: 24
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shuffle(int arr[], int n) {
srand(time(NULL));
int i, j, temp;
for (i = n - 1; i > 0; i--) {
j = rand() % (i + 1);
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
shuffle(arr, n);
printf("Shuffled array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
相关问题
用c语言写一个简单的洗牌发牌程序
以下是一个简单的洗牌发牌程序的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define CARD_NUM 52
int main()
{
int cards[CARD_NUM];
const char *suits[] = {"Clubs", "Diamonds", "Hearts", "Spades"};
const char *ranks[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
// 初始化牌堆
for (int i = 0; i < CARD_NUM; i++) {
cards[i] = i;
}
// 洗牌
srand(time(NULL));
for (int i = 0; i < CARD_NUM; i++) {
int j = rand() % CARD_NUM;
int temp = cards[i];
cards[i] = cards[j];
cards[j] = temp;
}
// 发牌
for (int i = 0; i < CARD_NUM; i++) {
int card = cards[i];
int suit = card / 13;
int rank = card % 13;
printf("%s of %s\n", ranks[rank], suits[suit]);
}
return 0;
}
```
该程序使用了一个52个元素的数组来表示一副扑克牌,其中每个元素表示一张牌,牌的值从0到51依次表示52张牌。程序首先初始化牌堆,然后使用srand()函数和time(NULL)函数来生成随机种子,接着使用rand()函数和模运算来实现洗牌,最后使用循环来遍历牌堆,将每张牌的花色和点数打印出来。
用c语言写一个洗牌发牌程序
由于洗牌发牌程序需要涉及到随机数,因此需要使用C语言中的random函数。下面是一个简单的洗牌发牌程序的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_CARDS 52
#define NUM_SUITS 4
#define NUM_RANKS 13
int main(void) {
int deck[NUM_CARDS];
const char *suits[NUM_SUITS] = {"Hearts", "Diamonds", "Clubs", "Spades"};
const char *ranks[NUM_RANKS] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
int i, j, n, temp;
srand(time(NULL)); // 设置随机数种子
// 初始化牌堆
for (i = 0; i < NUM_CARDS; i++) {
deck[i] = i;
}
// 洗牌
for (i = 0; i < NUM_CARDS; i++) {
j = rand() % NUM_CARDS;
temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
// 发牌
n = 0;
for (i = 0; i < NUM_SUITS; i++) {
printf("%s:\n", suits[i]);
for (j = 0; j < NUM_RANKS; j++) {
printf("%s of %s\n", ranks[deck[n] % NUM_RANKS], suits[deck[n] / NUM_RANKS]);
n++;
}
printf("\n");
}
return 0;
}
```
在这个程序中,首先定义了牌的个数、花色和点数,并初始化了一个整型数组deck,表示牌堆。然后使用srand函数来设置随机数种子,保证每次运行程序都会得到不同的结果。接着使用for循环来初始化牌堆,然后使用for循环洗牌,通过rand函数生成一个随机数j来交换deck[i]和deck[j]的值,从而达到洗牌的目的。最后使用for循环来发牌,将牌堆中的每张牌按花色和点数输出即可。
注意:这个程序中只是简单地输出了牌的点数和花色,如果需要更加复杂的发牌规则,需要进一步完善程序。