gpt4 book ai didi

java - 带有静态方法的数组

转载 作者:行者123 更新时间:2023-12-04 05:09:07 24 4
gpt4 key购买 nike

我正在尝试使用两种不同的静态方法来操作两个数组

  • double dot(double[]a, double[]b)
  • double[][] multiply(double[][]a, double[][]b) .

  • 我似乎无法弄清楚如何使用静态方法将两个数组相乘并将这些值输出给用户,但我相信我的点积方法很好。我知道我的乘法方法需要使用返回方法,但我不确定如何正确表示

    这是我到目前为止所拥有的:
    public class LibMatrix {

    public static void main(String[] args) {

    double[] a = { 8, 5, 6, 3, 2, 1 };
    double[] b = { 9, 8, 4, 1, 4, 7 };
    }

    public static double dot(double[] a, double[] b) {
    double sum = 0.0;
    for (int i = 0; i < a.length; i++)
    sum += a[i] * b[i];
    return sum;

    }

    public static double[][] multiply(double[][] a, double[][] b) {
    int n = 6;
    double[][] c = new double[n][n];
    for (int i = 0; i < n; i++)
    for (int j = 0; i < n; i++)
    c[i][j] = a[i][j] * b[i][j];
    return a;

    }
    }

    最佳答案

    以下是一些更正:

    public class LibMatrixTests
    {
    static class LibMatrix {
    public static double dot(double[] a, double[] b) {
    double sum = 0.0;
    for (int i = 0; i < a.length; i++)
    sum += a[i] * b[i];
    return sum;
    }
    public static double[][] mul( double[][] a, double[][] b ) {
    double[][] c = new double[a.length][a[0].length];
    for (int i = 0; i < a.length; i++)
    for (int j = 0; j < a[i].length; j++)
    c[i][j] = a[i][j] * b[i][j];
    return a;
    }
    }

    public static void main( String[] args ) {
    double[] a = { 8, 5, 6, 3, 2, 1 };
    double[] b = { 9, 8, 4, 1, 4, 7 };
    double[][] c = { a, b };
    double[][] d = { b, a };
    double e = LibMatrix.dot( a, b );
    double[][] f = LibMatrix.mul( c, d );
    System.out.println( e );
    for( double[] g : f ) {
    for( double h : g ) {
    System.out.print( h + ", " );
    }
    System.out.println();
    }
    }
    }

    输出:
    154.0
    8.0, 5.0, 6.0, 3.0, 2.0, 1.0,
    9.0, 8.0, 4.0, 1.0, 4.0, 7.0,

    关于java - 带有静态方法的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15118433/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com