C Program to Count Males and Females
You can define two variables to keep track of the number of boys and girls separately, then judge the gender of the input. Each time a gender is input, increment the corresponding variable, and in the end get the number of boys and girls.
Below is a simple example code in C language:
#include <stdio.h>
int main() {
int num_boys = 0;
int num_girls = 0;
char gender;
printf("请输入性别(男/女),输入'q'结束:\n");
while (1) {
scanf(" %c", &gender); // 注意前面的空格,避免读取上一个输入的换行符
if (gender == 'q') {
break;
} else if (gender == '男') {
num_boys++;
} else if (gender == '女') {
num_girls++;
} else {
printf("输入有误,请重新输入(男/女):\n");
}
}
printf("男生个数:%d\n", num_boys);
printf("女生个数:%d\n", num_girls);
return 0;
}
This code reads input one by one through an infinite loop until ‘q’ is entered to end the loop. Each time a gender is read, the corresponding variable is increased by one depending on the gender. Finally, it outputs the number of male and female.