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".
我想创建一个数组,其中每个元素总结函数“CosineEffect”的结果。例如,如果“heliostatNumber”为3,则“余弦”数组中的每个元素应该是函数“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;
}
2 个解决方案
#1
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;
#2
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
.
您不在代码中修改sum变量,它始终为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.
for循环中的条件也应该是10而不是11,因为你有10个元素的数组。
#1
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;
#2
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
.
您不在代码中修改sum变量,它始终为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.
for循环中的条件也应该是10而不是11,因为你有10个元素的数组。