gpt4 book ai didi

java - 使用标量乘法乘以 2D 矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 11:09:48 25 4
gpt4 key购买 nike

我必须编写一个程序来提示用户输入二维矩阵的尺寸以及矩阵的值。

之后,我必须将矩阵乘以 2 并打印结果。

我的程序即将完成,但我不知道如何乘以矩阵并将这些值存储到新矩阵中。这是我到目前为止的代码:

import java.util.Scanner; 

public class MatrixMultiplication {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Please enter the number of rows: ");
int row = sc.nextInt();

System.out.println("Please enter the number of columns: ");
int col = sc.nextInt();

int[][] matrix = new int[row][col];

System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: ");
for (row = 0; row < matrix.length; row++) {
for (col = 0; col < matrix[row].length; col++) {
matrix[row][col] = sc.nextInt();
}
}
System.out.println();

for (row = 0; row < matrix.length; row++) {
for (col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}

我到处寻求帮助并尝试了几种不同的说法,但似乎没有一个是完全正确的。

我知道我必须使用 for 循环,但就像我说的,我不完全确定要使用多少个,如何将新值存储在矩阵中并显示它,等等。

任何方向将不胜感激!

最佳答案

在第一个double-for-loop之后,您需要声明第二个矩阵,它将是第一个矩阵的元素,但*2,所以:

int[][] matrixDouble = new int[row][col];
for (row = 0; row < matrix.length; row++) {
for (col = 0; col < matrix[row].length; col++) {
matrixDouble[row][col] = matrix[row][col]*2; //element -> *2 -> store in new matrix
System.out.print(matrixDouble[row][col] + " ");
}
System.out.println();
}

在新矩阵的每个框中,它将在第一个矩阵中的相同位置存储数字,但存储2因子

可以同时打印

<小时/>

取决于您需要如何解决它,但您可以将操作移到第一个for循环中:

for (row = 0; row < matrix.length; row++) {
for (col = 0; col < matrix[row].length; col++) {
matrix[row][col] = sc.nextInt();
matrixDouble[row][col] = matrix[row][col]*2;
}
}

关于java - 使用标量乘法乘以 2D 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145290/

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