【问题描述】编写程序,从键盘输入n(n<10)本书的名称和定价并存入结构数组中,从中查找定价最高和最低的书的名称和定价,并输出
【输入形式】先输入书本数n(整型,n<10),再依次输入每本书的名称(字符串)和定价(实型)。
【输入输出样例】(下划线部分表示输入)
Input n:3
Input the name,price of the 1 book:C 21.5
Input the name,price of the 2 book:VB 18.5
Input the name,price of the 3 book:Delphi 25.0
The book with the max price:Delphi,price is:25.0
The book with the min price:VB,price is:18.5
【样例说明】
输出价格最高的书的名称和定价,再输出价格最低的书的名称和定价,格式为
The book with the max price:%s,price is:%0.1lf
The book with the min price:%s,price is:%0.1lf
标点符号全部为英文:
参考GPT和自己的思路:
好的,根据你的问题描述,我可以为你提供如下的计算机程序代码,来完成这个任务:
#include <stdio.h>
#define MAXN 10
struct Book {
char name[50];
double price;
};
int main() {
int n;
printf("Input n:");
scanf("%d", &n);
struct Book books[MAXN];
double maxPrice = -1;
double minPrice = 1e9;
int maxIndex, minIndex;
for (int i = 0; i < n; i++) {
printf("Input the name,price of the %d book:", i + 1);
scanf("%s%lf", books[i].name, &books[i].price);
if (books[i].price > maxPrice) {
maxPrice = books[i].price;
maxIndex = i;
}
if (books[i].price < minPrice) {
minPrice = books[i].price;
minIndex = i;
}
}
printf("The book with the max price:%s,price is:%0.1lf\n", books[maxIndex].name, maxPrice);
printf("The book with the min price:%s,price is:%0.1lf\n", books[minIndex].name, minPrice);
return 0;
}
这个程序首先会通过 scanf
函数从键盘输入书的数量 n
,然后依次输入每本书的名称和价格,并将它们存入一个结构体数组 books
中。同时,在输入过程中,它会记录下价格最高的书和价格最低的书的索引(标记为 maxIndex
和 minIndex
),并记录下它们的价格(标记为 maxPrice
和 minPrice
)。
最后,程序会按照要求输出价格最高和最低的书的名称和价格,其中需要使用 printf
函数和占位符 %s
和 %lf
来输出字符串和实型数据。
希望这个程序可以解决你的问题!