HI!
There is a piece of code which takes 'n' float or double numbers and calculates their average and then adds or subtracts to numbers so all of them reach to the average .
The reason I'm writing this code is for Programming Challenges (Challenge "The Trip" , page 17)
this is the simplified code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
//NOT COMPLETE
#include <iostream>
#include <iomanip>
using std :: cout ;
using std :: cin ;
using std :: endl ;
using std :: setprecision ;
using std :: fixed ;
int main ()
{
int n ;
float average , taken , given ;
cin >> n ;
while (n > 0)
{
average = 0 ;
taken = 0 ;
given = 0 ;
float exs [n] ;
for (int i = 0 ; i < n ; i ++)
cin >> exs [i] ;
for (int i = 0 ; i < n ; i ++)
average += exs [i] ;
average /= n ;
for (int i = 0 ; i < n ; i ++)
if (exs [i] - average > 0)
taken += exs [i] - average ;
else
given -= exs [i] - average ;
cout << fixed << setprecision (2) << (given > taken ? given : taken) << endl ;
cin >> n ;
}
return 0 ;
}
|
The reason I'm saying float has a strange behavior is this special case : (the same example the book gave)
we want this program for 4 numbers :
15.01
15.00
3.01
3.00
When I debug the program (in CodeBlocks GCC) and I watch how the values "average" and "exs [i]" changes during debugging.
And what I see is :
exs [0] = 15.0100002 (But I entered 15.01)
exs [1] = 15
exs [2] = 3.00999999 (But I entered 3.01)
exs [3] = 3
So the sum I get becomes 36.0200005 (Instead of 36.02)
and the average equals to 9.00500011 (Instead of 9.005)
And the the result I get becomes 12.00 (Instead of 11.99)
And then All the calculations go wrong.
Isn't there a way to fix it?
I'm not looking for another algorithms (for example getting the decimal and integers seperately) I just need a way to make the float calculate correctly.
THANK YOU ALL!