Summing up an Array: Error

Thanks for viewing my post. I am writing a program that reads an input file into an array. The next step is for me to sum up the values of the elements of the array. I understand the concept and the logic, however I get an error.

1
2
3
4
5
6
7
8
int monthSum(double sales[][MONTHS])
{
    int sum = 0;

    for(int i = 0; i < MONTHS; i++){
        sum += sales[i]
    }
}


The error is: invalid conversion from double to int. And I get it, I cant set an int type to a double. How can I get around this? the double sales array needs to stay double because it is a const double in a different function.

When I set sum to type double, I then get the error: invalid operands of types double and double to binary operator+


Any help is appreciated. Thanks!
Last edited on
It's not a double to int conversion problem. It's a double* to int conversion problem. Your function's parameter is a 2-dimensional array, and (assuming MONTHS is a constant), sales[i] is a 1-dimensional array. You need to specify which array index you want to add up to the sum:

sum+=sales[<something here>][i];
The problem here is that you're declaring sales to be doubly subscripted, but when you reference it at line 6, you're only using a single subscript.

The second problem is you never return sum and it's value will be lost.

Both the type of the function and sum should be double.


You need to specify which array index you want to add up to the sum:

sum+=sales[<something here>][i];


Is the "something here" a specific element? If so, I need all the elements in that specific column.
As in, the sum of all elements there?
You'll need to iterate over that one too in that case.
Topic archived. No new replies allowed.