C++面向对象编程题 第36题

36.建立一个类 Matrix,输入 5×5 的二维数组,编写程序实现:求出两对角线上各元素的和,求出对角线上行、列下标均为偶数的各元素的积,找出对角线上其值最大的元素以及它在数组中的位置。

具体要求如下:

  1. 私有数据成员
  • int array[5][5]:二维整型数组。
  • int sum:数组 array 两对角线元素的和。
  • int product:数组 array 对角线上行、列下标均为偶数的各元素的积
  • int max,x,y:数组 array 对角线上其值最大的元素以及它在数组中的位置。
  1. 公有成员函数
  • Matrix(int a[5][5]):构造函数,初始化成员数据。
  • void get_sum():求二维数组两对角线元素的和。
  • void get_product():求二维数组两对角线上行、列下标均为偶数的各元素的积。
  • void get_max():求二维数组两对角线上其值最大的元素和它在数组中的位置。
  • void print():输出二维数组(每行输出 5 个元素)及其它所求的值。
  1. 在主程序中对该类进行测试
#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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值