选举投票

使用数组

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

// 模拟投票
void vote(int count[]);
// 选择目的地
void choose(int count[]);

int main(void) {
  /*
   * 某班级组织野外郊游,想要在ABCD四个景点选择其中一个。
   * 现在班上有80名同学进行投票,找出投票数最多的景点
   *
   * 要求:
   *     1、学生投票,用随机数模拟
   *     2、如果多个景点投票一样的话,A优先于B,B优先于C,C优先于D
   * */
  int voteCount[4] = {0};
  vote(voteCount);
  choose(voteCount);

  return 0;
}

void vote(int count[]) {
  srand(time(NULL));
  for (int i = 0; i < 80; i++) {
    count[rand() % 4]++; // 简化
    /*
    switch (rand() % 4) {
    case 0:
      count[0]++;
      break;
    case 1:
      count[1]++;
      break;
    case 2:
      count[2]++;
      break;
    case 3:
      count[3]++;
      break;
    default:
      break;
    }
    */
  }
  for (int i = 0; i < 4; i++) {
    printf("%c Votes = %d\n", i + 65, count[i]);
  }
}

void choose(int count[]) {
  int max = count[0];
  char ch = 'A';
  for (int i = 0; i < 4; i++) {
    // 恰好满足顺序检查
    if (max < count[i]) {
      max = count[i];
      ch = i + 65;
    }
  }

  printf("Destination is %c\n", ch);
}

使用结构体

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

typedef struct Spot {
  char Name[20];
  int Count;
} Spot;

// 模拟投票
void vote(Spot count[], int length);
// 选择目的地
void choose(Spot count[], int length);

int main(void) {
  /*
   * 某班级组织野外郊游,想要在ABCD四个景点选择其中一个。
   * 现在班上有80名同学进行投票,找出投票数最多的景点
   *
   * 要求:
   *     1、学生投票,用随机数模拟
   *     2、如果多个景点投票一样的话,A优先于B,B优先于C,C优先于D
   * */
  Spot voteCount[] = {{"A", 0}, {"B", 0}, {"C", 0}, {"D", 0}};
  int len = sizeof(voteCount) / sizeof(Spot);

  vote(voteCount, len);
  choose(voteCount, len);

  return 0;
}

void vote(Spot count[], int length) {
  srand(time(NULL));
  for (int i = 0; i < 80; i++) {
    count[rand() % 4].Count++;
  }
  for (int i = 0; i < length; i++) {
    printf("%s Votes = %d\n", count[i].Name, count[i].Count);
  }
}

void choose(Spot count[], int length) {
  int counter = 0;
  int max = count[0].Count;
  for (int i = 0; i < length; i++) {
    if (max < count[i].Count) {
      counter = i;
      max = count[i].Count;
    }
  }

  printf("Destination is %s\n", count[counter].Name);
}
posted @ 2026-01-20 23:02  Zhuye_inking  阅读(0)  评论(0)    收藏  举报