我想写一个代码,用结构数组来记录书本及其价格,并输出价格最高和最低的书本名称和价格
struct Book {
char name[100];
float price;
};
//获取书的信息
int n;
printf("Enter the number of books: ");
scanf("%d", &n);
struct Book books[n];
for (int i = 0; i < n; i++) {
printf("Enter the name and price of book %d: ", i + 1);
scanf("%s %f", books[i].name, &books[i].price);
}
//找到价格最高和最低
float maxPrice = books[0].price;
float minPrice = books[0].price;
int maxIndex = 0;
int minIndex = 0;
for (int i = 1; i < n; i++) {
if (books[i].price > maxPrice) {
maxPrice = books[i].price;
maxIndex = i;
}
if (books[i].price < minPrice) {
minPrice = books[i].price;
minIndex = i;
}
}
//输出
printf("The highest priced book is %s at $%.2f\n", books[maxIndex].name, books[maxIndex].price);
printf("The lowest priced book is %s at $%.2f\n", books[minIndex].name, books[minIndex].price);