结构体 查找书籍

描述

给定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

天梯赛的题目,自己写一个结构体,然后用sort排序就行,比较简单,但是要注意gets函数带来的问题,做个简单处理,不然,输入会有问题的

#include <iostream>
#include <algorithm>
using namespace std;
struct node{
    char s[31];
    double n;
}t[101];
bool cmp(struct node a,struct node b)
{
    return a.n<b.n;
}
int main()
{
    int s,i,m,j,k;
    cin>>s;
    getchar();
    for(i=0;i<s;i++)
    {
        //scanf("
");
        gets(t[i].s);
        cin>>t[i].n;
        getchar();
    }
    sort(t,t+s,cmp);
    printf("%.2lf, %s
",t[s-1].n,t[s-1].s);
    printf("%.2lf, %s
",t[0].n,t[0].s);
}

需要注意的是由于输入s时,后面会按下回车键,因此需要scanf(" ");来避免gets碰到回车之后读不到后面的内容

原文地址:https://www.cnblogs.com/andrew3/p/8577174.html