int a[]={1,1,2,2};
int b[]={1,1,1,1,3,3,2,2};
int ab[]=new int[b.length];
我想乘ab[]= a[]* b[]
乘两个大小不等的java数组
ab []
应该是这样的= {1,1,2,2,3,3,4,4}
我尝试循环,但我不知道如何做到这一点,而这两个阵列大小不相等
int a[]={1,1,2,2};
int b[]={1,1,1,1,3,3,2,2};
int ab[]=new int[b.length];
我想乘ab[]= a[]* b[]
乘两个大小不等的java数组
ab []
应该是这样的= {1,1,2,2,3,3,4,4}
我尝试循环,但我不知道如何做到这一点,而这两个阵列大小不相等
int a[]={1,1,2,2};
int b[]={1,1,1,1,3,3,2,2};
int ab[]=new int[b.length];
for (int i=0 ; i<b.length ; i++) {
ab[i] = b[i] * a[i%a.length];
}
这应该给你正确的结果。但是我不检查数组长度,或者确保数组b
比数组a
长,所以请事先做好这一点。
这对我工作感谢 – john
你的意思是ab [] = {1,1,2,2,3,3,4,4}?那会使它成为b的大小。
假设一旦你得到了b中的索引4,你想循环返回到索引0,但是这应该是相当直接的代码 - 我已经使用C++ 14对它进行了编码。它应该是相当适应Java。
这里是输出:C:{1,1,2,2,3,3,4,4}
// Sample program to print out the product of two arrays
#include <iostream>
#include <type_traits>
int main(int argc, char* argv[])
{
int a[] = {1, 1, 2, 2};
int b[] = {1, 1, 1, 1, 3, 3, 2, 2};
constexpr auto lengthA = std::extent<decltype(a)>::value;
constexpr auto lengthB = std::extent<decltype(b)>::value;
int c[lengthB] = { 0 };
static_assert(lengthB > lengthA, "Length of b is expected to be greater than length of a!");
int indexA = 0;
for (int indexB = 0; indexB < lengthB; ++indexB)
{
c[indexB] = a[indexA] * b[indexB];
indexA = (indexA + 1) % lengthA;
}
// Lets print out the resultant array
std::cout << "C: {";
for (int indexC = 0; indexC < lengthB; ++indexC)
{
std::cout << c[indexC];
if (indexC < lengthB - 1)
{
std::cout << ", ";
}
}
std::cout << "}" << std::endl;
return 0;
}
编辑:在写一些代码,不编译的风险,这里的理论上的声音,但是未建的Java代码(只是真正重要的部分):
int a[]={1,1,2,2};
int b[]={1,1,1,1,3,3,2,2};
int ab[]=new int[b.length];
int indexA = 0;
for (int indexB = 0; indexB < b.length; ++indexB)
{
ab[indexB] = b[indexB]*a[indexA];
indexA = (indexA + 1) % a.length;
}
// At this point, ab should have what you need
你能详细说明你的乘法过程吗? – Atri
你用什么样的逻辑来进行乘法运算? – Abdelhak
在数组'b'上循环,并使用数组'a'的大小来给出数组'a'的乘数位置(我假设a0 * b0,a1 * b1,...,a0 * b4 ,a1 * b5,...,所以你只需要通过数组'b',但是循环访问数组'a',直到通过'b'once)。 – AntonH