[英]How can I create a matrix with Java and add all its elements to a sum?
我需要用Java編寫代碼來創建3000X3000矩陣,其中每個元素都是整數類型。 之后,我需要添加所有元素。
我得到了這段代碼:
public class matrix {
public static void main(String[] args) {
long sum = 0;
int dimension = 3000;
int i, j;
int matrix[][] = new int[dimension][dimension];
...
for (i=0; i<dimension; i++) {
for (j=0; j<dimension; j++) {
sum = sum + matrix[i][j];
}
}
}
}
但是由於我以前從未使用過數組,因此實際上我們今天才第一次談論數組。 我並沒有真正了解如何自定義此代碼,因此我最終得到了矩陣中所有元素的總和。
您可以使用兩個循環並遍歷數組並將整數值存儲在其中。
public static void main(String[] args) {
long sum = 0;
int dimension = 3000;
int i, j;
int matrix[][] = new int[dimension][dimension];
for (i = 0; i < dimension; i++) {
for (j = 0; j < dimension; j++) {
matrix[i][j] = 1; // Number you want to store, could be a scanner input
}
}
for (i = 0; i < dimension; i++) {
for (j = 0; j < dimension; j++) {
sum = sum + matrix[i][j];
}
}
System.out.println(sum);
}
數組只是一個東西的列表。 在Java中,矩陣是列表的列表,因此要訪問網格中的一個點,請訪問arr[y][x]
,其中x是x位置, y是y位置。
因此,要將所有內容加在一起,可以使用具有以下結構的代碼:
int sum = 0; // Define the sum to add to
int[][] grid = new int[] { // Define the grid
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
};
for (int x = 0; x < grid[0].length; x++) // Loop through X indicies
for (int y = 0; y < grid.length; y++) // Loop through Y indicies
sum += grid[y][x]; // Add value to the sum
該代碼循環遍歷每個整數,並將其加到總和上。 請記住,第一個索引是行,因此是y ,第二個索引是列,因此是x 。 您遍歷兩個索引,捕獲存儲在網格中的每個數字並將其存儲。
我修改了iNan的答案:
public static void main(String[] args) {
long sum = 0;
int dimension = 3000;
int i, j;
int matrix[][] = new int[dimension][dimension
for (i = 0; i < dimension; i++) {
for (j = 0; j < dimension; j++) {
matrix[i][j] = 1; // Number you want to store, could be a scanner input
sum = sum + matrix[i][j];
}
}
System.out.println(sum);
}
您無需在填充條目的矩陣上進行單獨迭代,然后再次對其進行迭代以將所有事物累加起來。 您可以一步一步進行填充和總結,從而可以稍微加快程序速度。 使用大型矩陣,可以大大加快程序運行速度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.