- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直在通过一些免费的在线教程自学 Java,并挑战自己完成几乎所有的练习。我已经在这个问题上坚持了一个星期了,这让我发疯。我觉得我已经相当接近了,只是被构成不均匀列的不同数组长度绊倒了。
public class Testing {
public static void main(String[] args) {
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
int sum = 0;
int row = 0;
int col = 0;
int currentRow = 0;
while (currentRow < data.length) {
for (col = 0; col < data[currentRow].length; col++) {
sum = 0;
for (row = 0; row < data.length; row++) {
System.out.println(data[row][col]);
sum += data[row][col];
}
System.out.println("Sum: " + sum);
}
currentRow++;
}
}
}
最佳答案
似乎有一个循环太多了。您的 while
遍历第一个维度,而 for(row...
遍历第二个维度。因此,无需通过 for(row. ..
尝试少用一个循环:
public class Testing {
public static void main(String[] args) {
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
int sum = 0;
for (int currentRow = 0; currentRow < data.length; currentRow++) {
sum = 0;
for (int col = 0; col < data[currentRow].length; col++) {
System.out.println(data[currentRow][col]);
sum += data[currentRow][col];
}
System.out.println("Sum: " + sum);
}
}
}
public class Testing {
public static void main(String[] args) {
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
// get max length of a row == number of columns
int length = 0;
for (int r = 0; r < data.length; r++) {
int currLength = data[r].length;
if(currLength>length) length = currLength;
}
// create array for column sums
int[] sums = new int[length];
// fill array with zeros
Arrays.fill(sums, 0);
// sum up
for (int currentRow = 0; currentRow < data.length; currentRow++) {
for (int col = 0; col < data[currentRow].length; col++) {
System.out.println(data[currentRow][col]);
sums[col] += data[currentRow][col];
}
}
// print sums
for (int i = 0; i < sums.length; i++) {
System.out.println(i + ": " + sums[i]);
}
}
}
关于java - 计算不均匀二维数组中的列总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24518180/
我需要在半径R的圆内生成一个均匀随机点。 我意识到,通过在区间 [0 ... 2π) 中选择均匀随机的角度,并在区间 (0 ... R) 中选择均匀随机的半径,我最终会得到更多的点朝向中心,因为对于两
我想在一个正方形内生成 N 个点(均匀地)。我怎样才能做到这一点? 最佳答案 非常酷的问题,比我想象的要困难得多,但这就是想法。有关于 n 边形的论文,但我只会做正方形。因此,圆的均匀分布是一个常见问
考虑以下示例: import itertools import numpy as np a = np.arange(0,5) b = np.arange(0,3) c = np.arange(0,7)
SQL Server 将一组值分成 5 组,每组的 sum(count) 应该均匀分布。 表仅包含 2 列 rid 和 count。 create table t1(rid int, count in
我有以下简单的 HTML。 A B C 和 CSS: ul { width: 100%; display: flex; flex-direction:
我是一名优秀的程序员,十分优秀!