java方法使用循环将元素与数组相乘 [英] java methods multiplying elements with in an array using a loop

查看:141
本文介绍了java方法使用循环将元素与数组相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义一个名为weightedSum()的Java方法,它以两个整数数组为参数。
方法使用一个循环将两个数组的相应元素相乘(即,将每个数组的第一个参数放在一起,然后将每个数组的第二个元素相乘,依此类推),并返回和这些产品(也是一个整数)。你可能会认为这两个数组的长度是相等的。

pre $ public int weightedSum(int [] a,int [] b)


{
int value;
int sum;

(int i = 0; i {
value = a [i] * b [i]
value = value + value;

}

返回值;

我在写这个方法时遇到了麻烦。我站在它接受阵列,但我有麻烦写出循环本身,以便乘数组中的每个单独的元素与对方阵列,所以pos [1] * pos [1],然后添加两个值togather with pos [2] + pos [2],并获得所有值的总和

解决方案

试试这个: / b>

  public long dotProduct(int [] a,int [] b){
if(a == null)throw新的IllegalArgumentException(一个数组不能为空);
if(b == null)抛出new IllegalArgumentException(b数组不能为null);
if(a.length!= b.length)抛出new IllegalArgumentException(数组必须具有相等的长度);
long sum = 0L;
for(int i = 0; i sum + = a [i] * b [i];
}
归还金额;
}


Define a Java method named weightedSum() that takes two integer arrays as its arguments. The method uses a loop to multiply corresponding elements of the two arrays together (i.e., it multiplies the first argument of each array together, followed by multiplying the second element of each array together, and so on) and returns the sum of those products (which is also an integer). You may assume that both arrays are of equal length.

public int weightedSum(int [] a ,int [] b)


    {
        int value;
        int sum ;

        for (int i = 0 ; i < a.length ; i++)
        {
            value = a[i] * b [i];
            value  = value +value ;

        }

        return value;

I am having trouble writing this method out for my assignment . I under stand it accepts to arrays but i am having trouble writing out the loop itself so that it multiplies each individual element of the array with its counterpart in the opposite array so pos [1] * pos [1] and then add the two values togather with pos [2] + pos[2] and to get the sum total for all the values

解决方案

Try this:

public long dotProduct(int [] a, int [] b) {
    if (a == null) throw new IllegalArgumentException("a array cannot be null");
    if (b == null) throw new IllegalArgumentException("b array cannot be null");
    if (a.length != b.length) throw new IllegalArgumentException("arrays must have equal lengths");
    long sum = 0L;
    for (int i = 0; i < a.length; i++) {
        sum += a[i]*b[i];
    }
    return sum;
}

这篇关于java方法使用循环将元素与数组相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆