fan123456 发表于 2020-2-27 22:04:41

c语言

本帖最后由 fan123456 于 2020-2-27 22:20 编辑

c语言编程题,结构数组, 请鱼友帮忙               
                           将数据赋给结构体数组,并按照年龄从大到小顺序输出
                              姓名         年龄            年薪
                              张三            32               34000
                              李四            24                20000
                           王五            27             32000

蒋博文 发表于 2020-2-27 22:18:38

能不能说清楚一点{:10_277:}

4goodworld 发表于 2020-2-27 22:44:59

本帖最后由 4goodworld 于 2020-2-27 22:46 编辑

struct worker {
        char name;
        int age;
        int salary;
};


int main() {

        worker person;
        worker temp;
        for (int i = 0; i < 3; i++) {
                printf("请输入姓名:\n");
                scanf("%s", person.name);
                printf("请输入年龄:\n");
                scanf("%d", &person.age);
                printf("请输入年薪:\n");
                scanf("%d", &person.salary);
        }
        //冒泡排序
        for (int x = 0; x < 3; x++) {
                for (int y = 0; y < 3-x; y++) {
                        if (person.age >person.age) {
                                temp = person;
                                person = person;
                                person = temp;
                        }

                }
        }

        printf("姓名    年龄    年薪\n");
        for (int z = 0; z < 3; z++) {
                printf("%s    %d    %d\n",person.name, person.age, person.salary );

        }
       return 0;
}

fan123456 发表于 2020-2-27 22:47:14

4goodworld 发表于 2020-2-27 22:44


不用加标头吗?#include

4goodworld 发表于 2020-2-27 22:49:52

fan123456 发表于 2020-2-27 22:47
不用加标头吗?#include

我把关键的部分复制了,没有全部复制,你看着改呗

fan123456 发表于 2020-2-27 23:04:00

4goodworld 发表于 2020-2-27 22:49
我把关键的部分复制了,没有全部复制,你看着改呗

嗯嗯,好的,谢谢了哈,

major_lyu 发表于 2020-2-27 23:18:10

本帖最后由 major_lyu 于 2020-2-27 23:20 编辑

给你写了个冒泡排序的。你可以用更高效的排序算法。

#include <stdio.h>

typedef struct
{
    char name;
    int age;
    int salary;
} Employee;

void sortEmployee(Employee ems[], int num) //对Employee结构体数组ems中的结构体按照年薪从高到低排序,num为数组元素个数
{
    for (int i = 0; i < num - 1; i++)
    {
      for (int j = 0; j < num -1; j++)
      {
            if (ems.salary < ems.salary)
            {
                Employee temp = ems;
                ems = ems;
                ems = temp;
            }
      }
    }
}

int main(void)
{
    Employee ems = {
      {"Zhang San", 32, 34000},
      {"Li Si", 24, 20000},
      {"Wang Wu", 27, 32000}};

    sortEmployee(ems, 3); // 调用排序函数。

    for (int i = 0; i< 3; i++)//输出排序结果
    {
      printf("%20s%4d   %8d\n", ems.name, ems.age, ems.salary);
    }
    return 0;
}
页: [1]
查看完整版本: c语言