有如下结构体:
struct book
{
char strName[100]; // 图书名称
int nQuantity; // 图书销量(册数)
float fPrice; // 图书单价
double fSales; // 图书销售额
};
定义一个结构体数组,输入五本书的信息(图书销售额 = 图书销量 * 单价),然后按照图书销量排序,输出排序结果;再按照图书销售额排序,输出排序结果。
解题思路:一个排序可以使用排序算法,定义一个struct book 结构体变量temp,用于排序中的交换;两个结构体变量可以直接赋值,如:list[i] = temp;
供参考:
#include <stdio.h>
struct book{
char strName[100]; // 图书名称
int nQuantity; // 图书销量(册数)
float fPrice; // 图书单价
double fSales; // 图书销售额
};
void print(struct book B[])
{
int i;
for (i = 0; i < 5; i++)
printf("%s %d %f %lf\n", B[i].strName, B[i].nQuantity, B[i].fPrice, B[i].fSales);
}
int main()
{
struct book Book[5], temp;
int i, j;
printf("输入五本书的信息:图书名称 图书销量 图书单价\n");
for (i = 0; i < 5; i++)
{
scanf("%s %d %f", Book[i].strName, &Book[i].nQuantity, &Book[i].fPrice);
Book[i].fSales = Book[i].nQuantity * Book[i].fPrice;
}
printf("按照图书销量排序:\n");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4 - i; j++) {
if (Book[j].nQuantity > Book[j + 1].nQuantity) {
temp = Book[j]; Book[j] = Book[j + 1]; Book[j + 1] = temp;
}
}
}
print(Book);
printf("图书销售额排序:\n");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4 - i; j++) {
if (Book[j].fSales > Book[j + 1].fSales) {
temp = Book[j]; Book[j] = Book[j + 1]; Book[j + 1] = temp;
}
}
}
print(Book);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
struct book
{
char strName[100]; // 图书名称
int nQuantity; // 图书销量(册数)
float fPrice; // 图书单价
double fSales; // 图书销售额
}book[8];
bool cmp(struct book a,struct book b){return a.nQuantity<b.nQuantity;}
bool cmp1(struct book a,struct book b){return a.fSales<b.fSales;}
int main(){
printf("图书名称 图书销量 图书单价\n");
for(int i=0;i<5;i++){
cin>>book[i].strName>>book[i].nQuantity>>book[i].fPrice;
book[i].fSales=book[i].fPrice*book[i].nQuantity;
}
sort(book,book+5,cmp);
printf("按照图书销量排序:\n");
for(int i=0;i<5;i++) printf("图书名称: %s 图书销量: %d 图书单价: %.2f 销售额: %.2lf\n",book[i].strName,book[i].nQuantity,book[i].fPrice,book[i].fSales);
sort(book,book+5,cmp1);
printf("按照图书销售额排序:\n");
for(int i=0;i<5;i++) printf("图书名称: %s 图书销量: %d 图书单价: %.2f 销售额: %.2lf\n",book[i].strName,book[i].nQuantity,book[i].fPrice,book[i].fSales);
return 0;
}