vendredi 26 juin 2015

Not getting consistent results from Average and Sum function [duplicate]

This question already has an answer here:

I have a user inputting an array of doubles and for the most part it seems to work but when i type in this set 3.5, 4.0, -3.5, -2.0, -1.8, -0.2. I get a sum of -5.55112e-17 and an average of -9.25186e-18 when both should be getting me a result of zero. When I type in other doubles that don't sum up to zero, I seem to get the correct result and I get the right results when I input integers. Any ideas? Plz lemme know if you need to see more of the code.

double getAverage(double array[], int size)
{
double sum = 0;
double average;


for (int i =0; i < size; i++)
{
    sum += array[i];
}
average = double(sum / size);
return average;
}

Here's my sum function.

double getSum(double array[], int size)
{
double sum = 0;
//#double average = 0;

for (int i = 0; i < size; i++)
{
    sum += array[i];
}
//#average = double(sum) / size;
return sum;

Aucun commentaire:

Enregistrer un commentaire