python 编写一个彩票游戏?

python 编写一个彩票游戏?,第1张

按照题目要求编写的Python程序如下

import random

numlist=random.sample(range(0,10),5)

while numlist[0]==0:

  numlist=random.sample(range(0,10),5)

num=int(''.join([str(i) for i in numlist]))

inputnum=int(input("输入号:"))

bonus=0

count=0

if inputnum==num:

bonus=10000

else:

for i in set(str(inputnum)):

if int(i) in numlist:

count+=1

bonus=1000*count

print("彩票号:%d" % num)

print("奖金:%d元" % bonus)

源代码(注意源代码的缩进)

使用结构体链表模拟彩票的摇奖机,来保证每次随机都是不同的数字。

数组也可以模拟,但是删除元素比较麻烦,用链表更快捷。

定义数组指针,动态分配内存。

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

typedef struct List {

 int number

 struct List*next

} ArrayList

ArrayList*createList(int)//创建链表,参数是链表的节点数 

void freeList(ArrayList*)//循环释放所有节点的内存

int deleteNode(ArrayList*,int)//删除节点,返回节点的数据 

main() {

 //动态创建内存

 int*numbers=(int*)calloc(7,sizeof(int))

 int*inNumbers=(int*)calloc(7,sizeof(int))

 //动态创建数组链表存放1-33个编号

 ArrayList*balls= createList(33)

 int i

 srand((unsigned)time(NULL))

 printf("请输入7个不同的数字(1-33):\n")

 for(i=0 i<7 i++) {

  *(numbers+i)=deleteNode(balls,rand()%(33-i))

  scanf("%d",inNumbers+i)

 }

 printf("随机产生的7个数字是:\n")

 for(i=0 i<7 i++) {

  printf("%d ",*(numbers+i))

 }

 printf("\n相同的数字:\n")

 //查找

 int j

 for(i=0 i<7 i++) {

  for(j=0 j<7 j++) {

   if(*(numbers+i)==*(inNumbers+j)) {

    printf("%d ",*(numbers+i))

    break

   }

  }

 }

 //释放内存

 free(numbers)

 free(inNumbers)

 freeList(balls)

}

ArrayList*createList(int n) {

 ArrayList*head=NULL,*end=NULL,*node=NULL

 end=head=(ArrayList*)malloc(sizeof(ArrayList))//head在删除和插入节点时有用。 不能删除head,也不能插入到head前面

 int i

 for(i=1 i<=n i++) {

  node=(ArrayList*)malloc(sizeof(ArrayList))

  node->number=i

  end->next=node

  end=node

 }

 end->next=NULL

 return head

}

void freeList(ArrayList*head) {

 ArrayList*node=head

 while(head!=NULL) {

  head=head->next

  free(node)

  node=head

 }

}

int deleteNode(ArrayList*head,int index) { //index节点索引(0-32),返回被删除的球的编号

 ArrayList*node=head->next,*temp=head

 int i=0,number

 while(i<index&&node!=NULL) {

  temp=node

  node=node->next

  i++

 }

 if(node!=NULL) {

  number=node->number

  temp->next=node->next

  free(node)

 }

 return number

}

运行结果

public class RandomDemo {

public static void main(String[] args) {

LotteryTicket lt = new LotteryTicket()

int red[] = lt.getRed()

System.out.print("随机生成的红球为:")

for(int i=0i<6i++){

System.out.print(" "+red[i])

}

System.out.print("\t蓝球为:"+lt.getBlue())

}

}

class LotteryTicket{彩票生成类

private int[] red = new int[6]

public int[] getRed(){//返回红球

int i =0

for(i<6i++){

red[i] = (int)(Math.random()*33) +1

for(int j=0j<ij++){//保证了重复,我个从认为这个彩票好像不能重复吧

if(red[i]==red[j]){

red[i] = (int)(Math.random()*33) +1

j=0

}

}

}

return red

}

public int getBlue(){//返回蓝球

return (int)(Math.random()*16) +1

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/11188594.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-14
下一篇2023-05-14

发表评论

登录后才能评论

评论列表(0条)

    保存