1.源代码
#include "fuctions.h"
int main(void){
int n;
static candidate p[50];
int stu[MAX]={0};
input(&n, p);
char sig='a';
while (sig!='*') {
vote(n, p, stu);
screen(stu, p, n);
scanf("%c",&sig);
}
}
#ifndef fuctions_h
#define fuctions_h
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#define MAX 30
typedef struct{
char name[50];
int votemon;
int votetuo;
} candidate;
int findCandidate(int n, candidate p[50], const char *input) {
int candidateNum;
if (sscanf(input, "%d", &candidateNum) == 1 && candidateNum >= 1 && candidateNum <= n) {
return candidateNum - 1;
}
for (int j = 0; j < n; j++) {
if (strcmp(input, p[j].name) == 0) {
return j;
}
}
return -1;
}
int cmp_mon(const void* e1, const void* e2)
{
return (int)(((candidate*)e1)->votemon
-((candidate*)e2)->votemon);
}
int cmp_tuo(const void* e1, const void* e2)
{
return (int)(((candidate*)e1)->votetuo
-((candidate*)e2)->votetuo);
}
void input(int *n,candidate p[50]){
scanf("%d",n);
getchar();
int t=0;
while (t<*n) {
printf("请输入第%d个候选人姓名:\n",t+1);
fgets(p[t].name, sizeof(p[t].name), stdin);
p[t].name[strcspn(p[t].name, "\n")] = '\0';
t++;
}
}
void vote(int n,candidate p[50],int stu[MAX]){
int i=0,temp;
while (1) {
printf("请输入学号完成投票(输入-1结束):");
scanf("%d",&temp);
getchar();
if(temp==-1){
break;
}
else{
stu[i]=temp;
for (int t=0; stu[t]!=0; t++) {
printf("%s %d/%d\n",p[t].name,p[t].votemon+p[t].votetuo,i+1);
}
printf("请输入你选择的班长:\n");
char monitor_input[50]={0};
gets(monitor_input);
int monitor = findCandidate(n, p, monitor_input);
p[monitor].votemon++;
printf("请输入你选择的团支书:\n");
char tuo_input[50];
gets(tuo_input);
int tuozhishu=findCandidate(n, p, tuo_input);
while(tuozhishu==monitor){
printf("你选择的团支书与班长不允许是同一人,请重新输入你选择的团支书:");
gets(tuo_input);
tuozhishu=findCandidate(n, p, tuo_input);
}
p[tuozhishu].votetuo++;
i++;
printf("你已完成投票,谢谢!\n");
}
}
}
void screen(int stu[MAX],candidate p[50],int n){
int t;
for ( t=0; stu[t]!=0; t++) {
printf("%d\n",stu[t]);
}
printf("总计%d个学生投票",t);
for (int i=0; i<n; i++) {
printf("%s(班长得%d票,团支书得%d票)\n",p[i].name,p[i].votemon,p[i].votetuo);
}
qsort(p, n, sizeof(candidate), cmp_mon);
printf("班长:\n");
for (int i=n-1; i>=0; i--) {
printf("%s (%d/%d)\n",p[i].name,p[i].votemon,t);
}
qsort(p, n, sizeof(candidate), cmp_tuo);
printf("团支书:\n");
for (int i=n-1; i>=0; i--) {
printf("%s (%d/%d)\n",p[i].name,p[i].votetuo,t);
}
}
#endif