以下是一個(gè)C語(yǔ)言實(shí)現(xiàn)的隨機(jī)抽獎(jiǎng)程序示例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int numParticipants, numWinners;
printf("請(qǐng)輸入?yún)⑴c抽獎(jiǎng)的人數(shù):");
scanf("%d", &numParticipants);
printf("請(qǐng)輸入中獎(jiǎng)人數(shù):");
scanf("%d", &numWinners);
if (numWinners > numParticipants) {
printf("中獎(jiǎng)人數(shù)不能大于參與人數(shù)!\n");
return 0;
}
// 使用當(dāng)前時(shí)間作為隨機(jī)數(shù)種子
srand(time(NULL));
int* participants = (int*)malloc(numParticipants * sizeof(int));
int* winners = (int*)malloc(numWinners * sizeof(int));
// 初始化參與者編號(hào)
for (int i = 0; i < numParticipants; i++) {
participants[i] = i + 1;
}
// 隨機(jī)抽獎(jiǎng)
for (int i = 0; i < numWinners; i++) {
int randIndex = rand() % numParticipants;
winners[i] = participants[randIndex];
// 將已中獎(jiǎng)的參與者從數(shù)組中刪除
for (int j = randIndex; j < numParticipants - 1; j++) {
participants[j] = participants[j + 1];
}
numParticipants--;
}
printf("中獎(jiǎng)?wù)呔幪?hào):");
for (int i = 0; i < numWinners; i++) {
printf("%d ", winners[i]);
}
printf("\n");
free(participants);
free(winners);
return 0;
}
該程序會(huì)先詢問(wèn)參與抽獎(jiǎng)的人數(shù)和中獎(jiǎng)人數(shù),然后使用隨機(jī)數(shù)生成器生成中獎(jiǎng)?wù)呔幪?hào),最后輸出中獎(jiǎng)?wù)叩木幪?hào)。請(qǐng)注意,該程序使用了動(dòng)態(tài)內(nèi)存分配,因此在使用完之后需要調(diào)用free
函數(shù)釋放內(nèi)存空間。