Calculate average in array

I have most the parts to this code working but need some guidance for two last calculations or at least one and i can figure the other one out.

I'm trying to find the average value for both:
1
2
3
4
double calculateAverageHarvest(int harvest[ ])
//calculate the average daily harvest after 30 days
double calculateAverageSales(int sales[ ])
//calculate the average apple sales after 30 days 


I have what i think should lead me to the answer below but I could be completely wrong. Please help, thanks!

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
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

double calculateAverageHarvest(int harvest[]){  
    double average = 0;
    double sum = 0;
    for(int i=0; i<30; i++){
        harvest[i] = i;
    }for(int i=0; i<30; i++){
        sum += harvest[i];
        average +=1;
        return sum/average;
    }
}


double calculateAverageSales(int sales[]){     
    double average = 0;
    double sum = 0;
    for(int i = 0; i < 30; i++){
        sum += sales[i];
        average +=1;
        return sum/average;
    }
}

int main()
{
    return 0;
}
Last edited on
You will have to work with an actual array to know whether your calculations of the average is correct or incorrect.

How about you declare an array in main and then pass it to the functions?
I'm checking it against this code checker:

In order to check that your function works correctly we call
your function in the following way:
We choose 30 random values (integers) between 5-43
We then pass that array to your function and check if the
result is as expected
Here are the results of your function, with the correct (expected)
results, first we print all 30 values that are in the array then
we print the correct answer and your answer, on the same line
28
20
20
20
36
33
19
16
40
7
7
33
15
40
25
21
6
25
24
38
40
5
15
22
24
14
33
15
35
12
22.9333 28
Is my error because I have an int and a double? I noticed the answer they are looking for is in float form to the 4 decimal places "22.9333" and my answer is coming out as an int "28"...
Last edited on
Yes. You should use the same data type 'double' or 'float' in your arrays.

If you use int, the program will cut off decimals.
I'm still doing something wrong. I updated the code above to what I'm running and the figures are still pretty off. I changed everything over to a double.
Problem is here:
1
2
average +=1;
return sum/average;


The return needs to be outside the loop.

Also the average is sum / number of days(30).

Same problem with calculateAverageSales()
Thank you so very much! I thought i had average setup to equal 30..so tired.
You are very welcome - have some sleep.
Topic archived. No new replies allowed.