代码之家  ›  专栏  ›  技术社区  ›  Lenin

将数组中的每个元素与另一个数组中的相应元素相乘

  •  0
  • Lenin  · 技术社区  · 2 年前

    这就是我想做的。

    Array1 = {2, 5, 3, 6}
    Array2 = {1.5, 1.2, 1.3, 1.4}
    

    然后将它们分别相乘,如下所示:

    2*1.5  5*1.2  3*1.3  6*1.4
    

    然后将结果放入另一个数组中

    Results = {3, 6, 3.9, 8.4}
    

    如何在VB中实现这一点。NET Windows窗体应用程序?

    1 回复  |  直到 2 年前
        1
  •  1
  •   41686d6564    2 年前

    通过LINQ使用 IEnumerable.Zip() 方法:

    Dim Results As Double() = Array1.Zip(Array2, Function(d1, d2) d1 * d2).ToArray()
    ' Print the result
    Console.WriteLine(String.Join(",", Results)) ' 3,6,3.9,8.4
    

    或者如果你喜欢用传统的方式,你可以使用 For 循环如下:

    Dim length As Integer = Math.Min(Array1.Length, Array2.Length)
    Dim Results(length - 1) As Double
    For i = 0 To length - 1
        Results(i) = Array1(i) * Array2(i)
    Next