结构体指针数组函数综合应用之改写选票系统

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct HouXuanRen
{
	char name[32];
	int tickets;
};

struct HouXuanRen* initHouXuanRen(struct HouXuanRen *p,int *hxrtotal)
{	
	int i=0;
	
	if(p == NULL)
	{
		printf("请输入有几个候选人参加\n");
		scanf("%d",hxrtotal);
		p = (struct HouXuanRen*)malloc(*hxrtotal*sizeof(struct HouXuanRen));
	}
	
	for(i = 0 ; i < *hxrtotal ; i++)
	{	
		p->tickets = 0;
		printf("请输入第%d个候选人的名字",i+1);
		scanf("%s",p->name);
		p++;
	}
	return p-*hxrtotal;
}

void printhxr(struct HouXuanRen *p,int *hxrtotal)
{
	int i;
	
	for(i = 0 ; i < *hxrtotal ; i++)
	{
		printf("名字:%s,票数:%d\n",p->name,p->tickets);
		p++;
	}
}

int toupiao(struct HouXuanRen *p,int *hxrtotal)
{
	int i;
	int j;
	int mark;
	int feipiao=0;
	int toupiaototal = 0;
	struct HouXuanRen *bak;
	char toupiaoren[32];
	
	bak = p;
	
	printf("请输入有几个投票人\n");
	scanf("%d",&toupiaototal);
	for(i = 0 ; i < toupiaototal ; i++)
	{	
		memset(toupiaoren,'\0',sizeof(toupiaoren));
		p = bak;
		mark = 0;
		printf("请输入第%d个人要投的候选人名字",i+1);
		scanf("%s",toupiaoren);
		for(j = 0 ; j < *hxrtotal ; j++)
		{
			if(strcmp(p->name,toupiaoren) == 0)
			{
				p->tickets++;
				mark = 1;
			}
			p++;
		}
			if(mark == 0)
			{
				printf("此票作废!!\n");
				feipiao++;
			}
	}
	return feipiao;
}

void printtoupiaohouxinxi(struct HouXuanRen *p,int *hxrtotal,int *feipiao)
{	
	int i;
	
	puts("\n投票后的结果");
	for(i = 0 ; i < *hxrtotal ;i++)
	{
		printf("候选人名字:%s,候选人票数%d\n",p->name,p->tickets);
		p++;
	}
	printf("废票数:%d\n",*feipiao);
	
}

struct HouXuanRen *getMax(struct HouXuanRen *p,int *hxrtotal)
{
	int  i;
	struct HouXuanRen *Max;
	
	Max = p;
	
	for(i = 1 ; i < *hxrtotal ;i++)
	{
		if(Max->tickets < p->tickets)
		{
			Max = p;
		}p++;	
	}
	return Max;
}

void printGetMax(struct HouXuanRen *p,struct HouXuanRen *Max,int *feipiao)
{
	
	printf("%s以%d票当选!!废票数为:%d",Max->name,Max->tickets,*feipiao);
}

int main()
{
	struct HouXuanRen *hxr = NULL;
	struct HouXuanRen *Max = NULL;
	
	//候选人初始化
	int hxrtotal = 0;
	int feipiao = 0;
	hxr = initHouXuanRen(hxr,&hxrtotal);
	
	//打印候选人名单
	printhxr(hxr,&hxrtotal);
	
	//投票人进行投票
	feipiao = toupiao(hxr,&hxrtotal);
	
	//打印投票后的候选人信息以及票数
	printtoupiaohouxinxi(hxr,&hxrtotal,&feipiao);
	
	//获取最多票数的候选人
	Max = getMax(hxr,&hxrtotal);
	
	//打印票数最多的候选人
	printGetMax(hxr,Max,&feipiao);

	
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值