编写程序,从键盘输入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
帮忙看看我的答案错在哪里?
我的答案如下:
#include<stdio.h>
struct book{
char name[10];
float price;
};
int main()
{
struct book a[10];
int min=0,max=0,n,i;
printf("Input n:");
scanf("%d",&n);
for(i=1;i<=n;i++){
printf("Input the name,price of the %d book:",i);
scanf("%s%f",a[i-1].name,&a[i-1].price);
if(a[i].price>a[max].price)
max=i;
if(a[i].price<a[min].price)
min=i;
}
printf("The book with the max price:%s,price is:%.1f\n",a[max].name,a[max].price);
printf("The book with the min price:%s,price is:%.1f\n",a[min].name,a[min].price);
return 0;
}
最后输出时最大的书和价格是正常的,但是最小的书和价格却输出错误,这是什么原因?

代码如下:

#include

typedef struct BOOK

{

char bookname[20];

float pay;

}BOOK;

void sert(BOOK *book)

{

int i, j;

BOOK tmp;

for (i = 0; i < 9; ++i)

{

for (j = 0; j < 10; ++j)

{

if (book[j].pay > book[j+1].pay)

{

tmp = book[j];

book[j] = book[j+1];

book[j+1] = tmp;

}

}

}

}

int main(void)

{

BOOK book[10];

int i;

for (i = 0; i < 10; ++i)

{

printf("输入第%d个书名与价钱:", i+1);

scanf(" %s %f", book[i].bookname, &book[i].pay);

}

sert(book);

for (i = 0; i < 10; ++i)

{

printf("%s[%.2f]", 

book[i].bookname, book[i].pay);

}

return 0;

}

扩展资料

C 数组允许定义可存储相同类型数据项的变量,结构是 C 编程中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。

为了定义结构,您必须使用 struct 语句。struct 语句定义了一个包含多个成员的新的数据类型,struct 语句的格式如下:

struct tag {
   member-list
   member-list
   member-list  
   ...} variable-list ;

tag 是结构体标签。

member-list 是标准的变量定义,比如 int i; 或者 float f,或者其他有效的变量定义。

variable-list 结构变量,定义在结构的末尾,最后一个分号之前,您可以指定一个或多个结构变量。下面是声明 Book 结构的方式:

struct Books{
  

char  title[50];   

char  author[50];   

char  subject[100];   

int   book_id;} 

book;

在一般情况下,tag、member-list、variable-list 这 3 部分至少要出现 2 个。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-05-23
(1)你的结构体没初始化,会出现乱码
(2) 排序有问题,你无论怎么排序 最大的都是第一次输入的那个数, 我建议你封装一个排序的函数,这样最好

如果对你有帮助 请给分本回答被网友采纳
第2个回答  2014-05-24
#include<stdio.h>
struct book{
char name[10];
float price;
};
int main()
{
struct book a[10];
int min=0,max=0,n,i;
printf("Input n:");
scanf("%d",&n);
for(i=1;i<=n;i++){//初始化和找最值分开
printf("Input the name,price of the %d book:",i);
scanf("%s%f",a[i-1].name,&a[i-1].price);

}
for(i=1;i<n;i++)
{
if(a[i].price>a[max].price)
max=i;
if(a[i].price<a[min].price)
min=i;

}
printf("The book with the max price:%s,price is:%.1f\n",a[max].name,a[max].price);
printf("The book with the min price:%s,price is:%.1f\n",a[min].name,a[min].price);
return 0;
}
相似回答