新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C语言实现随机抽奖程序,C语言实现随机点名器数组

发布时间:2023-08-18 07:59:53

C语言实现随机抽奖程序

以下是一个C语言实现的随机抽奖程序示例:
```c
#include
#include
#include
int main() {
int numParticipants, numWinners;
printf("请输入参与抽奖的人数:");
scanf("%d", &numParticipants);
printf("请输入中奖人数:");
scanf("%d", &numWinners);
if (numWinners > numParticipants) {
printf("中奖人数不能大于参与人数! ");
return 0;
}
// 使用当前时间作为随机数种子
srand(time(NULL));
int* participants = (int*)malloc(numParticipants * sizeof(int));
int* winners = (int*)malloc(numWinners * sizeof(int));
// 初始化参与者编号
for (int i = 0; i < numParticipants; i++) {
participants[i] = i + 1;
}
// 随机抽奖
for (int i = 0; i < numWinners; i++) {
int randIndex = rand() % numParticipants;
winners[i] = participants[randIndex];
// 将已中奖的参与者从数组中删除
for (int j = randIndex; j < numParticipants - 1; j++) {
participants[j] = participants[j + 1];
}
numParticipants--;
}
printf("中奖者编号:");
for (int i = 0; i < numWinners; i++) {
printf("%d ", winners[i]);
}
printf(" ");
free(participants);
free(winners);
return 0;
}
```
该程序会先询问参与抽奖的人数和中奖人数,然后使用随机数生成器生成中奖者编号,最后输出中奖者的编号。请注意,该程序使用了动态内存分配,因此在使用完以后需要调用`free`函数释放内存空间。