如何将数组中的所有元素相乘
How to multiply all elements in an array
我发现很难将数组的所有元素相乘。我正在编写两个元素数组,然后将这两个数组合并为一个负数数组。稍后,我想将该合并数组的所有元素相乘。这是我的尝试:
int mul = 0;
for (i = 0; i < negativecount; ++i)
{
mul = mul * merge[i];
}
cout << mul << endl;
}
我得到随机数作为答案。我该如何解决这个问题?
mul
的初始值必须为1。
不仅你的初始乘法值必须像牧马人说的那样是1。此外,您的合并数组的值对于了解您得到的答案很重要。
好好看看这一行:
mul = mul * merge[i];
你到底想在这里完成什么?因为你不是在乘以数组中的数字,而是乘以你的乘数?因为你的 'mul' 值最终取决于你的起始值、你的迭代次数和你的 merge[i] 值,所以它看起来是随机的。以下代码将为您提供 2 的 mul 值:
int mul = 2;
int negativecount = 10;
int *merge = (int*)malloc(10 * sizeof(int));
for (int i = 0; i < negativecount; ++i)
{
merge[i] = 1;
mul = mul * merge[i];
}
cout << mul << endl;
但我猜你想要的是:
for (int i = 0; i < negativecount; i++)
{
merge[i] = merge[i] * mul;
}
祝你好运!
正如@Neil Kirk 建议的那样,您可以使用 std::accumulate
:
int mul = std::accumulate(merge, merge + negativecount, 1, std::multiplies<int>());
对于 C++17 及更高版本,您可以使用 std::reduce
:
int mul = std::reduce(merge, merge + negativecount, 1, std::multiplies<int>());
其行为类似于 std::accumulate
。但是,使用 std::reduce
您还可以指定一个执行策略,这可能会使您的船漂浮:
int mul = std::reduce(std::execution::par, merge, merge + negativecount, 1, std::multiplies<int>());
我发现很难将数组的所有元素相乘。我正在编写两个元素数组,然后将这两个数组合并为一个负数数组。稍后,我想将该合并数组的所有元素相乘。这是我的尝试:
int mul = 0;
for (i = 0; i < negativecount; ++i)
{
mul = mul * merge[i];
}
cout << mul << endl;
}
我得到随机数作为答案。我该如何解决这个问题?
mul
的初始值必须为1。
不仅你的初始乘法值必须像牧马人说的那样是1。此外,您的合并数组的值对于了解您得到的答案很重要。
好好看看这一行:
mul = mul * merge[i];
你到底想在这里完成什么?因为你不是在乘以数组中的数字,而是乘以你的乘数?因为你的 'mul' 值最终取决于你的起始值、你的迭代次数和你的 merge[i] 值,所以它看起来是随机的。以下代码将为您提供 2 的 mul 值:
int mul = 2;
int negativecount = 10;
int *merge = (int*)malloc(10 * sizeof(int));
for (int i = 0; i < negativecount; ++i)
{
merge[i] = 1;
mul = mul * merge[i];
}
cout << mul << endl;
但我猜你想要的是:
for (int i = 0; i < negativecount; i++)
{
merge[i] = merge[i] * mul;
}
祝你好运!
正如@Neil Kirk 建议的那样,您可以使用 std::accumulate
:
int mul = std::accumulate(merge, merge + negativecount, 1, std::multiplies<int>());
对于 C++17 及更高版本,您可以使用 std::reduce
:
int mul = std::reduce(merge, merge + negativecount, 1, std::multiplies<int>());
其行为类似于 std::accumulate
。但是,使用 std::reduce
您还可以指定一个执行策略,这可能会使您的船漂浮:
int mul = std::reduce(std::execution::par, merge, merge + negativecount, 1, std::multiplies<int>());