hoffnung
hoffnung

Reputation: 49

Summing results of an function for each element of an array

I want to make an array, where each element sums up the result of a function"CosineEffect". For example if the "heliostatNumber" is 3, each element in the "Cosine" array should be the sum of three results of funcion"CosineEffect".

But when I print the result out, it seems that they dont add up. Instead each element is the value of just one result, not three results.

float Cosine[10];

    for(int i=0;i<11;i++)
    {
        float sum=0;
        for(int j=0; j<heliostatNumber;j++)
        {
            Cosine[i]=sum+CosineEffect(SunRay[i], ReflectedRay[j]);
        }
        cout<<"Cosine Effect = "<<Cosine[i]<<endl;
    }

Upvotes: 2

Views: 76

Answers (2)

Nikolay K
Nikolay K

Reputation: 3850

It's hard to tell the exact problem without rest of your code, but as I can see the problem is in this line

Cosine[i]=sum+CosineEffect(SunRay[i], ReflectedRay[j])

It should be

Cosine[i]+=CosineEffect(SunRay[i], ReflectedRay[j])

You don't modify sum variable in you code, it is always 0.

If you need sum somewhere else in the code, you should do it like this

 sum += CosineEffect(SunRay[i], ReflectedRay[j]);
 Cosine[i] = sum;

Also the condition in for loop should be 10 not 11, because you have array of 10 elements.

Upvotes: 1

Alex McMillan
Alex McMillan

Reputation: 17952

Try going through your code and thinking about the values of each variable at each step.

In particular, look at sum.

float sum = 0;
for(int j=0; j < heliostatNumber; j++)
{
    sum = sum + CosineEffect(SunRay[i], ReflectedRay[j]);
}

Cosine[i] = sum;

Upvotes: 1

Related Questions