实验9-5 查找书籍(结构体)

实验9-5 查找书籍 (20 分)
给定n本书的名称和定价,本题要求编写程序,查找并输出其中定价最高和最低的书的名称和定价。

输入格式:
输入第一行给出正整数n(<10),随后给出n本书的信息。每本书在一行中给出书名,即长度不超过30的字符串,随后一行中给出正实数价格。题目保证没有同样价格的书。

输出格式:
在一行中按照“价格, 书名”的格式先后输出价格最高和最低的书。价格保留2位小数。

输入样例:
3
Programming in C
21.5
Programming in VB
18.5
Programming in Delphi
25.0
输出样例:
25.00, Programming in Delphi
18.50, Programming in VB

思路上还是比较简单的:有点类似一个数字数组找最大、最小值 

#include<stdio.h>
struct book
{
	char name[100];
	double cost;
};
int main()
{
	struct book b[15];
	int n,i,index_min,index_max;
	int min=10000,max=-1;
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		getchar();    //后面用gets()函数接收字符串
//,所以这里必须处理掉输入的回车,否则会让gets()接收到第一个字符为'\n'
		gets(b[i].name);
		scanf("%lf",&b[i].cost);
		if(b[i].cost<min)
		{
			min=b[i].cost;
			index_min=i;
		}
		if(b[i].cost>max)
		{
			max=b[i].cost;
			index_max=i;
		}
	}
	printf("%.2lf, %s\n",b[index_max].cost,b[index_max].name);
	printf("%.2lf, %s\n",b[index_min].cost,b[index_min].name);
	
	return 0;
}

也可以使用另外两个结构变量来找最大最小值

#include <stdio.h>
struct book
{
    char name[32];  //书名
    double price;    //价格
}s[10], high, low;
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        scanf("\n");    //每次输入数字后都会有一个'\n',用scanf吞掉它
        gets(s[i].name);
        scanf("%lf",&s[i].price);
    }
        
    high = low = s[0];
    for (int i = 1; i < n; i++)
    {
        if (s[i].price > high.price)
            high = s[i];
        if (s[i].price < low.price)
            low = s[i];
    }
    printf("%.2lf, %s\n", high.price, high.name);
    printf("%.2lf, %s\n", low.price, low.name);

    return 0;
}

这里拿出这道题分享的原因是这道题的输入上有一个坑:

在输入一个数字后如果我们要使用%s来输入一个字符串的话,我们一定一定要注意!!!!!!

处理输入数字后面的‘\n’

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZZWWWFFF_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值