问题描述:有5本书,每本书包含书号,书名,作者,价格,出版社的信息,编写函数:1.输出5本书信息。2.输出价格最高的那本书的信息。3.输出价格最低的那本书信息。在主函数中使用这3个函数
问题连接:有5本书,每本书包含书号,书名,作者,价格,出版社的信息,编写函数:1.输出5本书信息。2.输出价格最高的那本书的信息。3.输出价格最低的那本书信息。在主函数中使用这3个函数-优快云社区
我的回复:
#include <stdio.h>
// #include <string.h>
struct MyBook {
char number[20]; // 书号
char title[100]; // 书名
char author[20]; // 作者
double price; // 单价
char publisher[100]; // 出版社
};
#define MAX_BOOKS 1 // 书的数量
MyBook myBooks[MAX_BOOKS]; // 书本列表
int HighestIndex = 0; // 最高价书的索引
int LowestIndex = 0; // 最低价书的索引
void inputData(); // 输入资料
void printData(int index); // 打印资料
int main() {
inputData();
printf("\n\n列印所有书本的资料:\n");
printData(-1);
printf("\n\n列印最高价的书本资料:\n");
printData(HighestIndex);
printf("\n\n列印最低价的书本资料:\n");
printData(LowestIndex);
return 0;
}
// 输入资料
void inputData() {
double highestPrice = 0.00; // 最高价
double lowestPrice = 999999.00; // 最低价
for (int index = 0; index < MAX_BOOKS; index++) {
// 如果严谨点,应该检测书号是否重复以及单价不能少于等于0
printf("--- 请输入第%d本书的资料 ---", index + 1);
printf("\n\t书号:");
scanf("%s", myBooks[index].number);
printf("\t书名:");
scanf("%s", myBooks[index].title);
printf("\t作者:");
scanf("%s", myBooks[index].author);
printf("\t单价:");
scanf("%lf", &myBooks[index].price);
printf("\t出版社:");
scanf("%s", myBooks[index].publisher);
// 比较最高价
if (myBooks[index].price > highestPrice) {
highestPrice = myBooks[index].price;
HighestIndex = index;
}
// 比较最低价
if (myBooks[index].price < lowestPrice) {
lowestPrice = myBooks[index].price;
LowestIndex = index;
}
}
}
// 打印资料
void printData(int index) {
int startNumber = 0;
int endNumber = MAX_BOOKS;
if (index != -1) {
startNumber = index;
endNumber = index + 1;
}
printf("================================================================\n");
for (int i = startNumber; i < endNumber; i++) {
printf("书 号:%s\n", myBooks[i].number);
printf("书 名:%s\n", myBooks[i].title);
printf("作 者:%s\n", myBooks[i].author);
printf("单 价:%6.2lf\n", myBooks[i].price);
printf("出版社:%s\n", myBooks[i].publisher);
printf("----------------------------------------------------------------\n");
}
}