36.建立一个类 Matrix,输入 5×5 的二维数组,编写程序实现:求出两对角线上各元素的和,求出对角线上行、列下标均为偶数的各元素的积,找出对角线上其值最大的元素以及它在数组中的位置。
具体要求如下:
- 私有数据成员
- int array[5][5]:二维整型数组。
- int sum:数组 array 两对角线元素的和。
- int product:数组 array 对角线上行、列下标均为偶数的各元素的积
- int max,x,y:数组 array 对角线上其值最大的元素以及它在数组中的位置。
- 公有成员函数
- Matrix(int a[5][5]):构造函数,初始化成员数据。
- void get_sum():求二维数组两对角线元素的和。
- void get_product():求二维数组两对角线上行、列下标均为偶数的各元素的积。
- void get_max():求二维数组两对角线上其值最大的元素和它在数组中的位置。
- void print():输出二维数组(每行输出 5 个元素)及其它所求的值。
- 在主程序中对该类进行测试
#include<iostream>
#include<cstring>
using namespace std;
class Matrix{
int array[5][5],sum,product,max,x,y;
public:
Matrix(int a[5][5]){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
array[i][j]=a[i][j];
}
}
x=y=sum=max=product=0;
}
void get_sum(){
for(int i=0;i<5;i++){
sum += array[i][i] + array[i][4-i];
}
//判断矩阵的阶数是否为奇数,若为奇数则减去矩阵中心那个数;5&1表示判断5的奇偶性,奇数返回1偶数返回0
sum = 5&1?sum-array[5/2][5/2]:sum;
}
void get_product(){
product = 1;
for(int i =0;i<5;i++){
for(int j =0;j<5;j++){
if(i==j||i+j==5-1){
if(i%2==0&&j%2==0){
product*=array[i][j];
}
}
}
}
}
void get_max(){
max = array[0][0];
for(int i =0;i<5;i++){
for(int j =0;j<5;j++){
if(i==j&&array[i][j]>max){
max = array[i][j];
x=i;
y=j;
}else if(i+j==5-1&&array[i][4+i-1]>max){
max = array[i][4+i-1];
x = i;
y = 4+i-1;
}
}
}
}
void print(){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cout<<array[i][j]<<' ';
}
cout<<endl;
}
cout<<"sum:"<<sum<<endl;
cout<<"product:"<<product<<endl;
cout<<"max,x,y:"<<max<<","<<x<<","<<y<<endl;
}
};
int main(){
int a[][5]{
{1,2,3,4,5},
{2,3,4,5,6},
{3,4,5,6,7},
{4,5,6,7,8},
{5,6,7,8,9},
};
Matrix m(a);
m.get_sum();
m.get_max();
m.get_product();
m.print();
system("pause");
return 0;
}