Sum of an Array problem

Hi everyone, first post here but I've been lurking for a lot longer I just can't find an answer through searching for this. I've got to sum the values of the array in two for loops but i can't get it to work, and I don't know where to start really, I'm getting errors like "'+=' : illegal, right operand has type 'float [1000]'" and "'+=' : 'int' differs in levels of indirection from 'float [1000]'". Any help would be much appreciated!
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
// The size of the array
#define WIDTH 1000
#define HEIGHT 2000

float array[HEIGHT][WIDTH];

int main(int argc, char *argv[])
{
	// Fill the array with data
	for (int y = 0; y < HEIGHT; ++y) {
		for (int x = 0; x < WIDTH; ++x) {
			array[y][x] = float(x + y);
		}
	}
	
        int sum=0;
	for (int i=0;i<HEIGHT;i++)
	{
		sum+=array[i];
	}
	
	cout << sum << endl;

	return 0;
}
You're trying to add a float to an int. You should cast the internet out the window for this ;)
Any chance of some actual help?
On line 16, change int to float.

(By the way, why even use float in the first place? You're only dealing with whole numbers, and if you ened decimal places you should sue doubles - never floats.)
Last edited on
Was given to me be a lecturer as I missed the class never got round to asking him if I could change stuff like that so attempted to make it work as it is. I've actually tried that before and I'm getting "+=' : illegal, right operand has type 'float [1000]'"

I think I might just change them.
Last edited on
How many dimensions does the array have? Hint: it is not 1000 dimensions.
Last edited on
2, I'm sure I'm going about this addition the wrong way, am I at least on the right track?
How did you fill the array? You should calculate the sum in a similar way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main(int argc, char *argv[])
{
	// Fill the array with data
	for (int y = 0; y < HEIGHT; ++y) 
	{
		for (int x = 0; x < WIDTH; ++x) 
		{
			array[y][x] = float(x + y);
		}
	}
	
	float sum = 0;

	for (int y = 0; y < HEIGHT; ++y) 
	{
		for (int x = 0; x < WIDTH; ++x) 
		{
			sum += array[y][x];
		}

		cout << "Sum: " << sum;
	}
	return 0;
}


So this is what I've got although its definately not the numbers I was expecting. Any clues where to go from here? Should I do the rows and columns seperate?
Swap lines 21 and 22 ;p
Right we're getting somewhere. Thanks for your help.

The cout is giving me 2.99712e+009. Is this because of the floats?
That means 2.99712 x 109. Basically the computer version of scientific notation.
Topic archived. No new replies allowed.