Salem already gave you guys the answer... it's the innaccuracy of a float... decimal math is very innacurate (in my experience to the tenth, or +/- 0.01)... if you keep running it, eventually you'll probably end up with the right answer... either way, it'll be hard to ensure the right answer every single time.
I modded your code a bit and came out with this output:
Code:
4
15.01
15
3
3.01
AVG: 9.005
AVG: 9.00488
$12.00
I used the same input as you... here's the code I used:
Code:
#include<iostream>
#include<cmath>
using namespace std;
inline double round(double X, int intk)
{
double k=static_cast<double>(intk);
return ( floor( X*pow(k,10.0) + 0.5) / pow(k,10) );
}
int main()
{
int n = 0;
while(cin >> n)
{
if(n == 0)
return 0;
double trip[1000] = {0};
double sum = 0,ans = 0;
for(int i=0;i<n;++i)
{
cin >> trip[i];
sum += trip[i];
}
double avg = sum/double(n);
cout << " AVG: " << avg << endl;
avg = round(avg,2);
cout << " AVG: " << avg << endl;
for(int i=0;i<n;++i)
if(trip[i] > avg)
ans += trip[i]-avg;
cout.setf(ios::fixed);
cout.precision(2);
cout << '$' << ans << endl;
}
return 0;
}
------------------------------------------------------------------------------------
EDIT 2:
------------------------------------------------------------------------------------
I rewrote your code to actually do some real rounding... the only thing is that it doesn't clear out the number it acutually rounded... my brain is fried and I've been working at it for 20 minutes, so I'm giving up on that part... here's what I have:
Code:
inline double round(double X, int k)
{
double decimal=X-static_cast<int>(X); //take out whole numbers
double half=(5.0/(pow(10.0,k))); //half of the requested decimal place
double decimaltemp;
//cout<<"K: "<<k<<endl<<"DECIMAL: "<<decimal<<endl<<"HALF: "<<half<<endl;
if(decimal>=half) //if it's bigger than that
{
//cout<<"ROUND UP"<<endl;
decimal+=1.0/(pow(10.0,k-1)); //add one to next biggest decimal
//cout<<"DECIMAL: "<<decimal<<endl;
/*
NOTE: do something here to get rid of the decimal that was just rounded.
you have to find out it's value and delete it from itself, leaving a zero in it's place.
decimaltemp=static_cast<int>(decimal*(pow(10.0,k)));
cout<<"DECMIALTEMP: "<<decimaltemp<<endl;
decimaltemp-=decimaltemp/pow(10.0,k);
cout<<"DECIMALTEMP: "<<decimaltemp<<endl;
decimal-=decimaltemp;
cout<<"DECIMAL: "<<decimal<<endl;
*/
return (static_cast<int>(X)+decimal); //return the next decimal + 1
}
else //if it's smaller
{
//cout<<"ROUND DOWN"<<endl;
//decimal=zeroout(decimal,k); //kill rounded to zero
return (static_cast<int>(X)+decimal);//return the next decimal
}
}
all the couts that I commented out are for debugging... you can just ignore those. this code gives me this output:
Code:
4
15
15.1
3
3.1
AVG: 9.05
AVG: 9.15
$11.80
4
15
15.1
3
3
AVG: 9.025
AVG: 9.025
$12.05
I'll leave it up to you to find out how to get rid of the .05 in there.