随笔 - 14  文章 - 0  评论 - 0  阅读 - 266

c语言书籍排序 多数组协同排序 按价格排序【书名同步】 带有空格的字符串读取

题目:

编写程序,从键盘输入 n (n<10)本书的名称和定价并存入结构数组中,按单价从小到大排序并输出排序后的书籍信息。

输入输出示例:括号内为说明,无需输入输出

输入样例:

3    (n=3)
Programming in C
21.5
Programming in VB
18.5
Programming in Delphi
20

输出样例:

Programming in VB 18.5
Programming in Delphi 20.0
Programming in C 21.5

代码实现:

#include <stdio.h>
#include <stdlib.h>
#include <string.h> // 包含 string.h 头文件以使用 strcspn 函数
#define N 1000 // 图书数组可能达到的最大长度

typedef struct tagbook {
char name[50]; // 图书名字
double price; // 图书价格
} Book;

//选择排序函数
void Sort(Book *L, int n) {
int i, j;
Book temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (L[j].price > L[j + 1].price) { // 升序排序,如果需要降序则改为 >
temp = L[j];
L[j] = L[j + 1];
L[j + 1] = temp;
}
}
}
}

/* 打印图书数组 */
void PrintBooks(Book *books, int size) {
for (int i = 0; i < size; i++) {
printf("%s %.1f\n", books[i].name, books[i].price);
}
}

int main() {
int n;
scanf("%d", &n); // 读取图书数量
getchar(); // 消耗掉后面的换行符

Book books[N]; // 创建图书数组
for (int i = 0; i < n; i++) {
fgets(books[i].name, 50, stdin); // 使用fgets读取包含空格的书名,限制长度为49
books[i].name[strcspn(books[i].name, "\n")] = 0; // 去除fgets读取的换行符
scanf("%lf", &books[i].price); // 读取价格
getchar(); // 消耗掉价格后面的换行符
}

Sort(books, n); // 对图书数组进行排序

PrintBooks(books, n); // 打印排序后的图书数组

return 0;
}

posted on   qh2028  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示