用java 编一个程序 定义一个n行n列的二维整数数组,赋初值,然后求出对角线上的元素之和。

如题所述

import java.util.Scanner;

public class Matrix {

public static void main(String[] args) {
// TODO Auto-generated method stub

System.out.println("请输入n*n数组,n=");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] a = new int[n][n];//定义n*n数组
int result = 0;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
System.out.println("请输入第"+i+"行,第"+j+"列元素:");
a[i][j]=sc.nextInt();
}
result +=a[i][i];
}
System.out.println("对角线元素和为:"+result);
}

}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-04-07
#include<iostream>
using namespace std;

int main()
{
int sum = 0;
int n = 0;
int **array;//指向整型的指针的指针.
cout << "请输入矩阵的维数:" << endl;
cin >> n;
array = new int*[n];//存放指针的数组.
for(int k = 0; k < n; k++)
{
array[k] = new int[n];//指向一个整型数组.
}
cout << "请输入n*n个值:" << endl;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cin >> array[i][j];
cout << array[i][j] << " ";
}
cout << endl;
}
for(int i = 0; i < n; i++)
sum += array[i][i];
cout << "两条对角线元素之和为:" << sum << endl;

system("pause");
return 0;
}

输出结果:输入格式

第一行为正整数N,此后N行,每行N个整数。

输出格式

任意选定两行进行调换后,可能的最大差值

输入样例

3 1 2 3 4 5 6 7 8 9

输出样例

16

提示

将第1行与第3行交换,8+9+6-4-1-2=16追问

用java编

相似回答