我们输入的书名仅包含3个字母,页码和价格。我的算法应该按价格(升序)对书籍进行排序。但是,我的函数输入错误,只能排序一次或两次。在这个问题中必须使用结构,并且只能使用stdlib或stdio库中的函数。
我尝试将冒泡排序与价格,页数和名称一起使用。我使用strcpy
交换名称。但是,这似乎没用。
#include <stdio.h>
#include <stdlib.h>
struct Book{
char name[3];
int pagecount;
int price;
};
void sorter(struct Book books[], int n){
int pass;
int temp;
char temp1[3];
int temp3;
int i;
for(pass=1;pass<n;pass++){
for(i=0;i<n;i++){
if(books[i].price> books[i+1].price){
temp=books[i].price;
books[i].price= books[i+1].price;
books[i+1].price=temp;
strcpy(temp1,books[i].name);
strcpy(books[i].name,books[i+1].name);
strcpy(books[i+1].name,temp1);
temp3= books[i].pagecount;
books[i].pagecount= books[i+1].pagecount;
books[i+1].pagecount=temp3;
}
}
}
for(i=0;i<n;i++){
printf("%d- %s: %d pages.", i+1, books[i].name,books[i].pagecount);
puts("\n");
}
}
int main(void) {
int n;
scanf("%d", &n);
struct Book books[n];
int i;
for(i=0;i<n;i++){
scanf("%3s%d%d",&books[i].name, &books[i].pagecount, &books[i].price);
}
sorter(books,n);
return 0;
}
输入:
3
LOT 528 10
MSB 340 7
TGH 727 8
预期输出:
1- MSB: 340 pages.
2- THG: 727 pages.
3- LOT: 528 pages.
实际输出:
1- MSB: 340 pages.
2- : 0 pages.
3- TGH: 727 pages.
答案 0 :(得分:1)
请始终启用编译器警告和错误。编译器是您的朋友,而不是您的敌人!
您的代码中有几个错误:
char[4]
,因为C字符串带有字符串终止符i = n - 1
,这意味着您的代码将访问books[i + 1] = books[n]
,即数组末尾的一个元素。scanf("%3s...)
项的指针错误,因此书名被写入内存中的某个位置,而不是预期的位置修复这些问题,简化交换代码并跳过冒泡排序中不必要的步骤,将产生以下代码,该代码给出了给定输入的预期输出。
#include <stdio.h>
#include <stdlib.h>
struct Book{
char name[4]; /* 3 letters + terminator */
unsigned int pagecount;
unsigned int price;
};
void sorter(struct Book *books, unsigned int n) {
unsigned int pass;
/* bubble up sort */
for (pass = 1; pass < n; pass++) {
unsigned int i;
/*
* each pass bubbles one book up, therefore we don't
* need to include that book in further passes
*/
for (i = 0; i < n - pass; i++) {
if (books[i].price > books[i+1].price) {
/* swap */
struct Book temp = books[i];
books[i] = books[i+1];
books[i+1] = temp;
}
}
}
for (pass = 0; pass < n; pass++) {
printf("%u- %s: %u pages.\n", pass+1, books[pass].name, books[pass].pagecount);
}
}
int main(void) {
unsigned int n;
if (scanf("%u", &n) < 1) {
fprintf(stderr, "Incorrect input for # of books\n");
return(1);
}
struct Book books[n];
unsigned int i;
for (i=0; i < n; i++) {
if (scanf("%3s%u%u",
books[i].name,
&books[i].pagecount,
&books[i].price) < 3) {
fprintf(stderr, "Incorrect input for book #%u\n", i+1);
return(1);
}
}
sorter(books, n);
return(0);
}