我有一个浮点数组arr[n][m]
,其中n
定义行数,m
定义列数,用户使用scanf()函数输入。每个元素都是根据以下公式计算的:
arr[i][j] = fabs(exp(i)-exp(j))+(i+j)/2.+1
我需要检查该元素是否从两侧都小于其neigbours的总和(在这种情况下,忽略底部和顶部,但也可以将它们计算在内)。它的计数几乎是正确的,但是由于某种原因,它忽略了位于最后两行中间的元素。然后,我必须找到这些元素的总和,并用其neigbours索引总和的平均值代替它们,计算i + j:
for (i = 0; i<n; ++i, puts(" ")) // it's easier to deal with the elements displayed in this way
for (j=1; j<m-1; ++j) // begin with the [0][1] because [0][0] doesn't have any neighbour on the left;
m-1 because the last element does not have any neighbour on the right
{
if (arr[i][j] < ((arr[i][j-1])+(arr[i][j+1])))
{
printf("%.2f ", arr[i][j]);
count++;
sum+= arr[i][j];
arr[i][j] = (i+j + i+j) / 4;
}
}
printf("\nThe number of such elements: %i", count);
printf("\nThe sum of such elements is: %.2f", sum);
因此,问题在于要对最后两行中的中间值进行计数并将它们包括在求和公式中。
答案 0 :(得分:2)
arr[i][j] = (i+j + i+j) / 4;
这行是做什么用的?您正在替换元素值,大多数情况下是用更小的值。这就是为什么比较失败的原因-左边的元素比以前小得多,因此总和不再大于中心元素。