鱼C论坛

 找回密码
 立即注册
查看: 2071|回复: 1

[萌新报道] 如何实现链表字符串交换?

[复制链接]
发表于 2022-1-6 00:31:14 | 显示全部楼层 |阅读模式
15鱼币
如何实现数字从大到小排序的同时,数字前面的名字也随着数字排序?
  1.         #include<stdio.h>
  2.         FILE *in,*out;
  3.         typedef struct
  4.         {
  5.           double x;
  6.           char name[10];
  7.         }STU;
  8.         STU stu[100];
  9.         int cmp(const void *a,const void *b)
  10.         {
  11.           return ((STU*)a)->x > ((STU*)b)->x ? -1:1;
  12.         }
  13.         int main()
  14.         {
  15.           int n,i,temp;
  16.           char temp_name[10];
  17.           char name[10];
  18.           in=fopen("use.txt","r");
  19.           out=fopen("B.txt","w");
  20.           n=0;
  21.           while(fscanf(in,"%s%lf,",stu[n].name,&stu[n].x)!=EOF)
  22.             n++;
  23.                 for (int j = 0; j < n - 1; j++)
  24.                 {
  25.                         for (int i = 0; i < n - 1 - j; i++)
  26.                         if (stu[i].x < stu[i+1].x)
  27.                         {
  28.                                 temp = stu[i].x;
  29.                                 stu[i].x = stu[i+1].x;
  30.                                 stu[i+1].x = temp;
  31.                         }
  32.                 }
  33.           for(i=0;i<n;i++)
  34.             fprintf(out,"%s %lf\n",stu[i].name,stu[i].x);
  35.           fclose(in);
  36.           fclose(out);
  37.           return 0;
  38.         }
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-1-6 09:05:48 From FishC Mobile | 显示全部楼层
本帖最后由 傻眼貓咪 于 2022-1-6 09:17 编辑

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. typedef struct{
  4.         int id;
  5.         char name[15];
  6. }fruit;

  7. int compare(const void *a, const void *b){
  8.         fruit *x = (fruit *)a;
  9.         fruit *y = (fruit *)b;
  10.         return (x->id - y->id);
  11. }

  12. int main()
  13. {
  14.         fruit arr[5] = {
  15.                 {2, "banana"},
  16.                 {7, "oren"},
  17.                 {3, "apple"},
  18.                 {4, "watermelon"},
  19.                 {6, "strawberry"}
  20.         };
  21.         qsort(arr, 5, sizeof(fruit), compare);
  22.        
  23.         for(int i = 0; i < 5; i++) printf("id:%d fruit:%s\n", arr[i].id, arr[i].name);
  24.         return 0;
  25. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-24 17:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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