乘法后如何在数组中添加每个索引

时间:2019-04-21 17:02:52

标签: java

我不能保留两个数组的相乘索引并将其相加,它总是保留并相乘最后一个索引。

在此示例中,我具有值{1、2、3}和权重{0.1、0.2、0.7},它应该执行以下操作:1 * 0.1 + 2 * 0.2 + 3 * 0.7将给我2.6 。

我这样做1 * 0.1、2 * 0.2和3 * 0.7没问题,但是它只保留最后一个索引,而给我2.1。

public static void main(String[] args) 
{
    double[] values = {1, 2, 3};
    double[] weights = {0.1, 0.2, 0.7};
    System.out.println(weightedSum(values, weights));
}

public static double weightedSum(double[] values, double[] weights)
{
    double multiply = 0;    
    double sum = 0; 
    for (int i = 0; i < values.length; i++){ 
        multiply = values[i]*weights[i];
    }
    return multiply;
}

3 个答案:

答案 0 :(得分:2)

您将返回multiply,而不对sum做任何事情。而是对被乘数执行加法运算,然后将其添加到sum。喜欢,

public static double weightedSum(double[] values, double[] weights) {
    double sum = 0;
    for (int i = 0; i < values.length; i++) {
        sum += values[i] * weights[i];
    }
    return sum;
}

答案 1 :(得分:1)

只要两个数组的长度相同,最简单的解决方案如下:

    //Multiply two arrays of size 3 and output sum
    int arr1[] = {1,2,3};
    double arr2[] = {0.1, 0.2, 0.7};
    final int LENGTH = 3;
    double result = 0;
    for(int i=0; i < LENGTH; i++) {
        result += arr1[i]*arr2[i];
    }
    NumberFormat formatter = new DecimalFormat("#0.00");     
    System.out.println("The result is " + formatter.format(result));

答案 2 :(得分:1)

// functional style - The easiest solution as long as two arrays are of same length is following:

public static double weightedSum(double[] values, double[] weights) {
    return IntStream.rangeClosed(1, values.length)
                    .mapToDouble( i -> values[i] * weights[i])
                    .sum();
}