7-1 查找书籍(20 分)(程序设计天梯赛模拟练习题)

7-1 查找书籍(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
作者: C课程组
单位: 浙江大学
时间限制: 400ms
内存限制: 64MB
代码长度限制: 1

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<sstream>
using namespace std;

struct book {
	double money;
	string name;
};

bool compare(const book &a, const book &b)
{
	return a.money > b.money;
}

int main(void)
{
	struct book book[12];
	int n;
	cin >> n;
	getchar();
	for (int i = 0; i < n; i++) {
		getline(cin, book[i].name);
		cin >> book[i].money;
		getchar();//就是这忘了考虑233333
		//cout << i << " " << book[i].money << " " << book[i].name << endl;
	}

	sort(book, book + n, compare);

	printf("%.2lf, ", book[0].money);
	cout << book[0].name << endl;
	printf("%.2lf, ", book[n - 1].money);
	cout << book[n-1].name << endl;

	return 0;
}


注释:读取数字后要用getchar函数读取换行符,再读取字符串

这是渣渣的又一道细节没注意好的水题

猜你喜欢

转载自blog.csdn.net/mofadiyu/article/details/79749348