题目描述
编写以下函数:
(1)在一个二维数组中形成以下形式的n阶矩阵:
[1 1 1 1 1
2 1 1 1 1
3 2 1 1 1
4 3 2 1 1
5 4 3 2 1]
(2)去掉靠边的元素,生成新的n-2阶矩阵;
(3)求生成的n阶矩阵主对角线上的元素之和;
(4)以方阵形式输出数组。
在main函数中调用以上函数进行测试。
输入
输入生成矩阵的阶数(n>=2)
输出
以方阵形式输出生成的n阶矩阵、去掉靠边的元素生成的新的n-2阶矩阵、以及生成的n阶矩阵主对角线上的元素之和,最后一行要回车
样例输入
5
样例输出
Generated matrix:
1 1 1 1 1
2 1 1 1 1
3 2 1 1 1
4 3 2 1 1
5 4 3 2 1
del the elements on the side:
1 1 1
2 1 1
3 2 1
The sum of the diagonal:5
#include
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main() {
while(1){
int a;
cin>>a;//输入一个数
int array[a][a];//创建n阶数组
for (int i=0;i<a;i++)//赋值
for (int j=0;j<a;j++)
{
if(j<i)
array[i][j]=i+1-j;
else
array[i][j]=1;
}
cout<<"Generated matrix:"<<endl;
for (int i=0;i<a;i++)//输出这个 n阶数组
{
for (int j=0;j<a;j++)
{
cout<<array[i][j];
}
cout<<endl;
}
cout<<"del the elements on the side:"<<endl;
for (int i=1;i<a-1;i++)//少一圈的n阶数组
{
for (int j=1;j<a-1;j++)
{
cout<<array[i][j];
}
cout<<endl;
}
int sum=0;//计算
int i,j;
for (i = a - 2 ,j = 1 ; i >= 1 ; i-- , j++)//对角
{
sum+=array[i][j];//累加
}
cout<<"The sum of the diagonal:"<<sum<<endl;
}
return 0;
}
int main()
{
int nArr[5][5] = {0};
int nSum = 0;
for (int i = 0;i < 5;i ++)
{
cin>>nArr[i][0]>>nArr[i][1]>>nArr[i][2]>>nArr[i][3]>>nArr[i][4];
}
cout <<"\n矩阵如下:\n";
for (int i = 0;i < 5;i ++)
{
for (int j = 0;j < 5;j ++)
{
cout<<nArr[i][j] <<" ";
}
cout<<endl;
}
cout <<"新矩阵如下:\n";
for(int i = 1;i < 4;i ++)
{
for (int j = 1;j < 4;j ++)
{
cout<<nArr[i][j] <<" ";
if (i == j)
{
nSum += nArr[i][j];
}
}
cout<<endl;
}
cout << nSum <<endl;
return 0;
}
一个简单的思路。。。