0
点赞
收藏
分享

微信扫一扫

数据结构练习题--计票系统 C++

自由的美人鱼 2022-01-23 阅读 70

【题目】:通过C/C++实现唱票统计系统,输入所有的选举情况,后台自动计票

输入:lisa lisa benz benz audi etc

输出:lisa :2 票;benz 2 票;audi 1 票;etc 1 票;

【分析】

使用线性表将投票的数据存储,然后通过算法将对表中的元素统计出现的次数;

【答案】代码中含有解析,不懂的欢迎提问哦

       

#include <iostream>
#include<malloc.h>
#include <conio.h>
using namespace std;

typedef struct sqlist {
	string Candidate[100];//存放线性表地址
	int length=0;	   //存放线性表长度
}SqList;//定义线性表
void Input(SqList* L) {
	cout << "请输入代表数:";
	int Num = 0;
	cin >> Num;
	L->length = Num;
	cout << "请开始唱票:\n";
	for (int i = 0; i < L->length; i++) {//使用for循环将选举的人名字输入进去
		cin >> L->Candidate[i];
	}
}
void Voting_result(SqList* L) {
	int n = 0;
	cout << "投票结果如下:\n";
	string temp;
	int count1=0;
	string name[20];//用来存储选举后存储名字
	int count[20];//用来存贮选举后的票数            其中的name数组和count数组通过赋值的方式达到了一一对应关系
	temp = L->Candidate[0];//将一开始的选举人的名字赋值给temp
	for (int i = 0; i < L->length; i++) {
		int count1 = 0;//先前计票为0
		if (temp != L->Candidate[i])temp = L->Candidate[i];//首次判断时,temp == L->Candidate[i],这里判断的时选举人的名字
		for (int j = 0; j < L->length; j++) {
			if (L->Candidate[j] == temp)count1++;//在选票中选中temp的,则count+1
			if (j + 1 == L->length) {//判断是否为最后一张选票,是则将得到的选举人和票数存储起来,便于输出
				name[i] = temp;
				count[i] = count1;
			}
		}
	}
	for (int k = 0; name[k] != ""; k++) {
		if (name[k] == name[k + 1])continue;
		cout << "候选人" << name[k] << "得票统计:" << count[k] << endl;
	}
	cout << "测试结束!!!";
}
int main() {
	SqList L;
	Input(&L);
	Voting_result(&L);
	return 0;
}
举报

相关推荐

0 条评论