I've solved The trip from Programming Challenges. My solution suffers from lack of floating-point precision, though.
The problem:
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.
For example, if you have:
4
15.00
15.01
3.00
3.01
The output should be:
$11.99
My code:
#include <iostream>
#include <iomanip>
using namespace std;
float two_precision(float n){
return n - float((n*100.0-(int)(n*100))/100.0);
}
int main(){
int n; cin >> n;
float *v, sum, avg, dif;
while(n){
sum = dif = 0.0;
v = new float[n];
for(int i = n-1; i >= 0; i--){
cin >> v[i];
sum += v[i];
}
avg = (1.0*sum)/n;
for(int i = n-1; i >= 0; i--)
if(two_precision(v[i]-avg > 0))
dif = two_precision(dif + two_precision(v[i]-avg));
cout << '$';
cout << fixed << setprecision(2) << dif << endl;
delete v;
cin >> n;
}
return 0;
}
I have one case to show the error:
5
15.04
15.17
30.32
39.99
78.99
0
The output should be $47.17
and my code returns $47.16
.