千路论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 126|回复: 0

用C语言完成一个员工薪水计算程序

[复制链接]
小轻代发 发表于 2023-3-21 16:38:11 | 显示全部楼层 |阅读模式

马上注册,发布并获取更多一手信息。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
用 C语言完成:①设计一个员工的结构体,包含编号和薪水。②设计一个函数输入n个员工的信息。
③设计一个函数,找到n个员工薪水的平均值和中位数,并打印出薪水介于平均值和中位数之间的员工信息。
  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. typedef struct {
  4.     int id;
  5.     float salary;
  6. } Employee;

  7. void inputEmployees(Employee employees[], int n) {
  8.     for (int i = 0; i < n; i++) {
  9.         printf("请输入员工编号和薪水 (如:1 5000): ");
  10.         scanf("%d %f", &employees[i].id, &employees[i].salary);
  11.     }
  12. }

  13. float averageSalary(Employee employees[], int n) {
  14.     float sum = 0;
  15.     for (int i = 0; i < n; i++) {
  16.         sum += employees[i].salary;
  17.     }
  18.     return sum / n;
  19. }

  20. int compare(const void *a, const void *b) {
  21.     float diff = ((Employee *)a)->salary - ((Employee *)b)->salary;
  22.     return (diff > 0) - (diff < 0);
  23. }

  24. float medianSalary(Employee employees[], int n) {
  25.     qsort(employees, n, sizeof(Employee), compare);
  26.     return (n % 2 != 0) ? employees[n/2].salary : (employees[n/2 - 1].salary + employees[n/2].salary) / 2;
  27. }

  28. void printEmployeesBetweenAverageAndMedian(Employee employees[], int n) {
  29.     float average = averageSalary(employees, n);
  30.     float median = medianSalary(employees, n);

  31.     printf("平均薪水: %.2f\n", average);
  32.     printf("中位数薪水: %.2f\n", median);

  33.     printf("薪水介于平均值和中位数之间的员工信息:\n");
  34.     for (int i = 0; i < n; i++) {
  35.         if (employees[i].salary > average && employees[i].salary < median) {
  36.             printf("员工编号: %d, 薪水: %.2f\n", employees[i].id, employees[i].salary);
  37.         }
  38.     }
  39. }

  40. int main() {
  41.     int n;
  42.     printf("请输入员工数量: ");
  43.     scanf("%d", &n);

  44.     Employee employees[n];

  45.     inputEmployees(employees, n);
  46.     printEmployeesBetweenAverageAndMedian(employees, n);

  47.     return 0;
  48. }
复制代码
这个程序首先定义了一个员工结构体,包含员工编号和薪水。然后,它实现了几个函数:输入n个员工的信息、计算平均薪水、计算中位数薪水,以及打印薪水在平均值和中位数之间的员工信息。程序的主函数首先获取员工数量,然后调用这些函数完成任务。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

QQ|Archiver|手机版|小黑屋|千里行风 ( 鄂ICP备20010066号-2 )|网站地图

GMT+8, 2024-3-29 05:23 , Processed in 0.131833 second(s), 25 queries .

Powered by Discuz! X3.4 Licensed

© 2022- Qroad.cc Inc.

快速回复 返回顶部 返回列表