7-4 查找书籍 (15 分)
给定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 <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
using namespace std;
double n;
pair<string, double> book[10];
int main()
{
cin >> n;
cin.ignore();
double max1 = -1, min1 = 9999;
int t1, t2;
for (int i = 0; i < n; i++)
{
getline(cin, book[i].first);
cin >> book[i].second;
cin.ignore();
}
for (int i = 0; i < n; i++)
{
if (max1 < book[i].second)
t1 = i, max1 = book[i].second;
if (min1 > book[i].second)
t2 = i, min1 = book[i].second;
}
printf("%.2f, ", book[t1].second);
cout << book[t1].first << endl;
printf("%.2f, ", book[t2].second);
cout << book[t2].first << endl;
return 0;
}