c语言链表怎么求性别占比
时间: 2023-08-10 10:39:38 浏览: 37
要求链表中性别占比,需要先遍历链表,统计男性和女性的个数,然后计算出各自所占的比例。
以下是一个示例代码,假设链表中每个节点都有一个gender字段表示性别,0表示女性,1表示男性:
```c
struct Node {
int gender;
struct Node *next;
};
void genderRatio(struct Node *head) {
int maleCount = 0;
int femaleCount = 0;
struct Node *p = head;
while (p != NULL) {
if (p->gender == 0) {
femaleCount++;
} else if (p->gender == 1) {
maleCount++;
}
p = p->next;
}
float maleRatio = (float) maleCount / (maleCount + femaleCount);
float femaleRatio = (float) femaleCount / (maleCount + femaleCount);
printf("Male ratio: %.2f\n", maleRatio);
printf("Female ratio: %.2f\n", femaleRatio);
}
```
这个函数遍历链表,统计男性和女性的个数,然后计算出占比并打印输出。注意,我们使用了float类型来存储比例,以保留小数点后两位。