基本上我需要向用户查询矩阵。然后我需要找到A ^ 2,A ^ 3,A ^ 4 ......等等(其中A是矩阵)。然后我需要找到总和A + A ^ 2 + A ^ 3 ...等到6。
到目前为止,这就是我所做的
public class Driver {
public static void main(String[] args) {
int i, j, l, k, sum = 0 ;
int matrixAColumnSize ;
int matrixARowSize ;
double numberOfNodes ;
// Querying user for matrix size
matrixARowSize = Tools.queryForInt("Enter the row size of Matrix A: ") ;
matrixAColumnSize = Tools.queryForInt("Enter the column size of Matrix A: ") ;
// Creating Matrices
double matrixA[][] = new double[matrixARowSize][matrixAColumnSize] ;
double finalMatrix[][] = new double [matrixARowSize][matrixAColumnSize] ;
double tempMatrix[][] = new double[matrixARowSize][matrixAColumnSize] ;
numberOfNodes = Tools.queryForInt("Enter by how much you'd like to raise to the power: ") ;
// Creating Matrix A
for (i = 0; i < matrixARowSize; i++) {
for (j = 0; j < matrixAColumnSize; j++) {
matrixA[i][j] = Tools.queryForInt("Enter element in Matrix A" + (i+1) + "," + (j+1) + ": " ) ; }}
// Math
for (i = 0; i < matrixARowSize; i++)
{
for (j = 0; j < matrixAColumnSize; j++)
{
{
sum += Math.pow(matrixA[i][j], numberOfNodes) ;
}
finalMatrix[i][j] = sum ;
sum = 0;
}}
//Printing out matrix
System.out.println("Final: ") ;
for (i = 0; i < matrixARowSize; i++) {
for (j = 0; j < matrixAColumnSize; j++)
System.out.print(finalMatrix[i][j] + "\t") ;
System.out.println();
}
} }
它不起作用...... :(大笑
PS:Tools.queryForInt是我创建的用于查询用户的方法......
程序本身正在运行,但结果不正确。例如,
2 2 * 2 2 = 8 8
2 2 2 2 8 8
该计划会给我
4 4
4 4
所以当我升到2的幂时,它只是将数组中的所有内容提升2 ......
答案 0 :(得分:0)
计算矩阵的方式不正确。实际上你正在计算单个矩阵元素的功效。 在乘以矩阵之前,您应该检查它们的尺寸。对于AxB,A中的列数应该等于B中的列数。由于矩阵与自身相乘,它应该是一个方阵。
这是我用来乘以两个矩阵的代码。您可以修改此代码以满足您的要求。我建议递归或迭代地调用这个模块
for(int i=0;i<row;i++){
for(int j=0;i<col;i++){
for(int k=0;i<row;i++){
matrix[i][j]+=(A[i][k]*B[k][j]);
}
}
}