Code:
#include <stdio.h>
#include <stdlib.h>
void sumFloats(double xArray[], int numFloats){
int j, k;
double sumArray = 0.0;
for(j=0; j < numFloats - 1; j++){
for(k = j + 1; k < numFloats; k++){
if(*(xArray + j) >= *(xArray + k)){
double temp = *(xArray +j);
*(xArray + j) = *(xArray + k);
*(xArray + k) = temp;
}
}
}
for(k = 0; k < numFloats; k++){
printf("xArray[%d]: %f\n", k, xArray[k]);
sumArray = sumArray + xArray[k];
}
printf("Sum of the array is: %f\n", sumArray);
printf("The sum of the Array should be : 55325789.8739346\n\n");
}
int main (void)
{
double myarray[] = { .3476789, 1004008.67, .0000099, 1.3435678, 78.345678, 54321678.567, 22.6 };
sumFloats(myarray, sizeof(myarray) / sizeof(*myarray));
return 0;
}
#if 0
My output:
xArray[0]: 0.000010
xArray[1]: 0.347679
xArray[2]: 1.343568
xArray[3]: 22.600000
xArray[4]: 78.345678
xArray[5]: 1004008.670000
xArray[6]: 54321678.567000
Sum of the array is: 55325789.873935
The sum of the Array should be : 55325789.8739346
#endif
Apart from this single change, notice that I'm using double instead of float here. The larger precision of a double seems to fix your problem. You might be pedantic and say that 55325789.873935 != 55325789.8739346, but it's damn close. If you really need a number so precise, though, I recommend using gmp instead.