我最近刚刚在Java工作。我仍然在与Java进行一些斗争。任务是分别对列和行进行求和,示例如下。 我设法得到列的总和,但我总是在我想要的输出中重复第一行,我该如何删除该错误。并且只需要所需的列总和。
它如何分别对行的总和起作用?
非常感谢您的帮助
代码如下:
public class MatrixColumnSums {
public static void main(String[] args) {
// TODO Auto-generated method stub
double [][] a = new double [2][3];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
System.out.println( "A");
for (int i = 0; i < a.length; i++) {
String str = "";
for (int j = 0; j < a[i].length; j++) {
str += a[i][j] + "\t";
}
System.out.println(str);
}
// column sums
// creating another matrix to store the sum of columns matrices
double c[] = new double [a[0].length];
// Adding and printing addition of 2 matrices
System.out.println("C");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++)
{
c[j] += a[i][j];
System.out.print(c[j] + "\t");
}
System.out.println();
}
}
}
输出如下所示:
A
1.0 2.0 3.0
4.0 5.0 6.0
C
1.0 2.0 3.0(&lt; =我想删除此行)
5.0 7.0 9.0(我只想把它作为我的输出)
答案 0 :(得分:1)
**矩阵列总和**
doOneColumnSum方法求和一列。
private static double doOneColumnSum(double[][] arr, int col){
double total = 0;
for (int row = 0; row < arr.length; row += 1){
total += arr[row][col];
}
return total;
}
doColumnSums方法使用doOneColumnSum方法对所有列求和
public static double[] doColumnSums(double[][] arr)
{
int numColumns = arr[0].length;
double[] result = new double[numColumns];
for (int col = 0; col < numColumns; col += 1)
{
result[col] = findOneColumnSum(arr, col);
}
return result;
}
答案 1 :(得分:0)
在汇总 storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
print(error!)
return
}
if let profileImageUrl = metadata?.downloadURL()?.absoluteString {
let values = ["name": name, "email": email, "profileImageUrl": profileImageUrl]
self.registerUserIntoDatabaseWithUID(uid, values: values as [String : AnyObject])
}
})
}
})
}
fileprivate func registerUserIntoDatabaseWithUID(_ uid: String, values: [String: AnyObject]) {
let ref = Database.database().reference()
let usersReference = ref.child("users").child(uid)
usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
if err != nil {
print(err!)
return
}
矩阵时不要打印,只需在末尾打印一次:
c
请注意,我们可以在原始嵌套循环中添加// sum the columns first
for (int i=0; i < a.length; i++) {
for (int j=0; j < a[0].length; j++) {
c[j] += a[i][j];
}
}
// then iterate c[] once at the end and print it
for (int j=0; j < a[0].length; j++) {
System.out.print(c[j] + "\t");
}
逻辑,仅在求和完成后打印if
,但上面写的内容从关注点分离看起来更具吸引力