帮我写一个按name首字母排序的C语言;结构体为struct book //书 { char name[30]; //名 double price; //价格 int lent=0; //是否已借 0为空1为未借2为已借 int id=NULL; //图书编号 }stu[max];
时间: 2023-12-16 20:06:14 浏览: 41
好的,以下是按照name首字母排序的C语言代码:
```c
#include<stdio.h>
#include<string.h>
#define max 100
struct book {
char name[30];
double price;
int lent;
int id;
}stu[max];
void sort(struct book stu[],int n) {
int i,j;
struct book temp;
for(i=0;i<n-1;i++) {
for(j=0;j<n-1-i;j++) {
if(strcmp(stu[j].name,stu[j+1].name)>0) {
temp=stu[j];
stu[j]=stu[j+1];
stu[j+1]=temp;
}
}
}
}
int main() {
int n,i;
printf("输入书的数量:");
scanf("%d",&n);
printf("输入每本书的名字、价格、是否已借、图书编号(用空格隔开):\n");
for(i=0;i<n;i++) {
scanf("%s %lf %d %d",stu[i].name,&stu[i].price,&stu[i].lent,&stu[i].id);
}
sort(stu,n);
printf("按照name首字母排序后的书:\n");
for(i=0;i<n;i++) {
printf("%s %.2f %d %d\n",stu[i].name,stu[i].price,stu[i].lent,stu[i].id);
}
return 0;
}
```
代码说明:
1. 首先定义了一个结构体 `struct book`,包含了书的名字、价格、是否已借和图书编号。
2. 然后定义了一个排序函数 `sort`,使用冒泡排序法按照书名首字母进行排序。
3. 在 `main` 函数中,首先输入了书的数量和每本书的信息。
4. 然后调用 `sort` 函数进行排序。
5. 最后输出按照书名首字母排序后的书的信息。
注意事项:
1. 代码中使用了 `strcmp` 函数来比较字符串大小,需要在程序开头包含头文件 `string.h`。
2. 代码中使用了宏定义 `max` 来定义结构体数组 `stu` 的最大长度,需要在程序开头进行定义。