c语言程序怎么选票

时间:2025-01-25 11:23:15 单机游戏

在C语言中,编写选票统计程序可以通过以下几种方法实现:

方法一:简单投票程序

初始化票数:

为每个候选人设置初始票数为0。

读取投票:

循环读取20个投票,每个投票对应一个字符(A、B、C或D)。

统计票数:

根据读取到的字符,增加相应候选人的票数。

输出结果:

输出每个候选人的最终票数。

```c

include

int main() {

int a = 0, b = 0, c = 0, d = 0;

int i;

char ch;

printf("Please Enter your choices for A, B, C, or D (enter 0 to finish):\n");

for (i = 1; i <= 20; i++) {

scanf(" %c", &ch); // 注意前面的空格,用于跳过换行符

switch (ch) {

case 'A':

a++;

break;

case 'B':

b++;

break;

case 'C':

c++;

break;

case 'D':

d++;

break;

default:

break;

}

}

printf("A=%3d\tB=%3d\tC=%3d\tD=%3d\n", a, b, c, d);

return 0;

}

```

方法二:处理选票文件

读取选票数据:

从一个文件中读取选票数据,每条记录表示一个人的投票情况。

统计票数:

遍历选票数据,统计每个候选人的票数。

输出结果:

将统计结果输出到另一个文件。

```c

include

include

void ReadDat(char *filename, char xx[]) {

FILE *fp = fopen(filename, "r");

if (fp == NULL) {

perror("Error opening file");

return;

}

int i = 0;

while (fgets(xx[i], 10, fp)) {

i++;

}

fclose(fp);

}

void CountRs(char xx[], int yy[]) {

int a = 0, b = 0, c = 0, d = 0;

for (int i = 0; i < 100; i++) {

if (xx[i] == '1') a++;

if (xx[i] == '1') b++;

if (xx[i] == '1') c++;

if (xx[i] == '1') d++;

}

yy = a;

yy = b;

yy = c;

yy = d;

}

void writeDat(char *filename, int yy[]) {

FILE *fp = fopen(filename, "w");

if (fp == NULL) {

perror("Error opening file");

return;

}

fprintf(fp, "Candidate A: %d\n", yy);

fprintf(fp, "Candidate B: %d\n", yy);

fprintf(fp, "Candidate C: %d\n", yy);

fprintf(fp, "Candidate D: %d\n", yy);

fclose(fp);

}

int main() {

char xx;

int yy;

ReadDat("IN.DAT", xx);

CountRs(xx, yy);

writeDat("OUT.DAT", yy);

return 0;

}

```

方法三:使用结构体数组

定义结构体:

定义一个结构体数组来存储候选人信息和票数。

输入投票:

循环读取投票,更新结构体数组中的票数。

输出结果:

输出每个候选人的最终票数。