您的位置:首页 > 其它

UVA 10137 - The Trip

2017-08-09 14:48 537 查看
A number of students are members of a club that travels annually to exotic locations. Their destinations in the past have included Indianapolis, Phoenix, Nashville, Philadelphia, San Jose, and Atlanta. This spring they are planning a trip to Eindhoven.

The group agrees in advance to share expenses equally, but it is not practical to have them share every expense as it occurs. So individuals in the group pay for particular things, like meals, hotels, taxi rides, plane tickets, etc. After the trip, each student’s expenses are tallied and money is exchanged so that the net cost to each is the same, to within one cent. In the past, this money exchange has been tedious and time consuming. Your job is to compute, from a list of expenses, the minimum amount of money that must change hands in order to equalize (within a cent) all the students’ costs.

Input

Standard input will contain the information for several trips. The information for each trip consists of a line containing a positive integer, n, the number of students on the trip, followed by n lines of input, each containing the amount, in dollars and cents, spent by a student. There are no more than 1000 students and no student spent more than $10,000.00. A single line containing 0 follows the information for the last trip.

Output

For each trip, output a line stating the total amount of money, in dollars and cents, that must be exchanged to equalize the students’ costs.

Sample Input

3

10.00

20.00

30.00

4

15.00

15.01

3.00

3.01

0

Sample Output

$10.00

$11.99

题意:一组学生去旅行,每个学生花费的数额是不一样的,现在需要计算将钱出的少的学生,需要拿出的钱来给钱出的多的学生,并且拿出的钱的总额是最少的(在一美分以内)。

思路:我们首先需要知道的是平均每人需要出的钱数,为了要得到最少的交换钱数,我们设置了两个变量用于分别用于存储钱出的多的学生多处的钱数和钱出的少的少出钱数,去两者最小值。

注意:在这一题中需要注意的是浮点数的精度的舍取,可以使用sprintf函数和sscanf函数来格式化数据,m表示保留的小数位数,data是要格式化的数据

sprintf(temp, “%.mlf”, data)

sscanf(temp, “%lf”, &data)

#include <stdio.h>

using namespace std;

int main()
{
int n;//the number of students
double spent[1005];//the spent by student
char temp[1005];
while(scanf("%d", &n) == 1 && n){
double sumSpent = 0;
double averageSpent = 0;
double exchange1 = 0;//exchanged dollars
double exchange2 = 0;
for(int i = 0; i < n; i++){
scanf("%lf", &spent[i]);
sumSpent += spent[i];
}
averageSpent = sumSpent / n;
sprintf(temp, "%.2lf", averageSpent);
sscanf(temp, "%lf", &averageSpent);
for(int i = 0; i < n; i++){
if(spent[i] < averageSpent){
exchange1 += averageSpent - spent[i];
}
else{
exchange2 += spent[i] - averageSpent;
}
}
if(exchange1 < exchange2)
printf("$%.2lf\n", exchange1);
else
printf("$%.2lf\n", exchange2);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva