簡體   English   中英

乘法后如何在數組中添加每個索引

[英]How to add each indices in the array after multiplying them

我不能保留兩個數組的相乘索引並將其相加,它總是保留並相乘最后一個索引。

對於此示例,我具有值{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;
}

您返回的是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;
}

只要兩個數組的長度相同,最簡單的解決方案如下:

    //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));
// 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM