首页 > 解决方案 > C中的和积

问题描述

不确定这是什么技术术语,但我试图在 C 中将两个大小相等的数组相乘。我希望它像 Excel 中的 sumproduct 一样工作;将某个位置的每个数字相乘并将它们相加。

我想要的是:

correctResult = [0] * [0] + [1] * [1] + [2] * [2]

我不想要的是两个 foo 循环给出的结果:

incorrectResult = [0] * [0] + [0] *[1] + [0] * [2] + ... + [2] * [1] + [2] * [2]

这可能与循环吗?我对多个两个 2D 数组有疑问,但我认为相同的概念适用于 1D 或 2D。

标签: c

解决方案


For 1D Array , solution would be like this :

Suppose two arrays are A & B of equal size n

int result = 0;
for(int i = 0; i < n; i++)
{
    result = result + A[i]*B[i];
}

推荐阅读