矩阵乘法错误:不兼容的类型(浮点到整数)

时间:2019-07-04 09:13:38

标签: java arrays matrix multidimensional-array casting

这是我的矩阵乘法代码:

import java.util.*;
class MatrixMult{
  static float[][] matMult(float[][] a, float[][] b){
    float[][] c = new float[a.length][b[0].length];
    for(int i = 0; i < a.length; ++i){
      for(int j = 0; j < a[0].length; ++j){
        float sum = 0;
        for(int z = 0; z < b.length; ++z){
          sum += a[i][z] * b[z][j];
        }
        c[i][j] = sum;
      }
    }
    for(int i = 0; i < c.length; i++){
      for(int j = 0; j < c[0].length; j++){
        System.out.print(c[i][j] + " ");
      }
      System.out.println();
    }
    return c;
  }
  public static void main(String[] arg){
    Scanner sc = new Scanner(System.in);
    System.out.println("number of columns and rows for array a: ");
    float arow = sc.nextFloat();
    float acol = sc.nextFloat();
    float[][] a = new float[arow][acol]; //error1
    System.out.println("elements of array a: ");
    for(int i = 0; i < a.length; i++){
      for(int j = 0; j < a[0].length; j++){
        a[i][j] = sc.nextFloat();
      }
    }
    System.out.println("number of columns and rows for array b: ");
    float brow = sc.nextFloat();
    float bcol = sc.nextFloat();
    float[][] b = new float[brow][bcol]; //error2
    System.out.println("elements of array b: ");
    for(int i = 0; i < b.length; i++){
      for(int j = 0; j < b[0].length; j++){
        b[i][j] = sc.nextFloat();
      }
    }
    matMult(a, b);
  }
}

我评论了应该是“错误”的两行,但是我不知道如何解决它,出现以下错误:不兼容的类型:可能从int到float的有损转换。

1 个答案:

答案 0 :(得分:2)

这里的问题是您正在使用float而不是int作为大小初始化数组。

float arow = sc.nextFloat();
float acol = sc.nextFloat();

// this definition is invalid as array initializer expect an integer 
// and not a floating point number
float[][] a = new float[arow][acol]; //error1

您应该读取矩阵大小的整数,并用它们初始化两个二维数组。

int arow = sc.nextInt();
int acol = sc.nextInt();

// No error all is good
float[][] a = new float[arow][acol];