#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 定义结构体
struct Employee {
int empID;
char name[30];
float salary;
};
// 比较函数,用于qsort从高到低排序
int compare(const void *a, const void *b) {
struct Employee *empA = (struct Employee *)a;
struct Employee *empB = (struct Employee *)b;
if (empA->salary < empB->salary) return 1;
if (empA->salary > empB->salary) return -1;
return 0;
}
int main() {
struct Employee employees[] = {
{1, "Alice", 5000.0},
{2, "Bob", 6000.0},
{3, "Charlie", 4500.0},
{4, "David", 7000.0}
};
int numEmployees = sizeof(employees) / sizeof(employees[0]);
// 排序
qsort(employees, numEmployees, sizeof(struct Employee), compare);
// 计算平均工资
float totalSalary = 0;
for (int i = 0; i < numEmployees; i++) {
totalSalary += employees[i].salary;
}
float averageSalary = totalSalary / numEmployees;
// 打印工资高于平均工资的员工信息并计算总和
float highSalaryTotal = 0;
printf("工资高于平均工资的员工信息:\n");
for (int i = 0; i < numEmployees; i++) {
if (employees[i].salary > averageSalary) {
printf("员工ID: %d, 姓名: %s, 工资: %.2f\n", employees[i].empID, employees[i].name, employees[i].salary);
highSalaryTotal += employees[i].salary;
}
}
printf("这些员工工资总和: %.2f\n", highSalaryTotal);
return 0;
}
- 结构体定义:首先定义了
struct Employee
结构体,包含员工ID、姓名和工资信息。
- 比较函数:
compare
函数用于qsort
库函数,实现从高到低的排序逻辑。
- 排序:使用
qsort
对employees
数组进行排序。
- 计算平均工资:遍历数组计算所有员工工资总和,再除以员工数量得到平均工资。
- 打印与求和:再次遍历数组,打印工资高于平均工资的员工信息,并累加这些员工的工资得到总和。