c++ 每日一练 day3

题目

//3.建立一个矩阵类Matrix,存储一个4 * 4的矩阵并能在矩阵中查找某数。要求如下:
//(1)私有数据成员
//int p[4][4]:存储一个4 * 4的矩阵的值。
//int n:矩阵的行数。
//int x:存储根据查找要求在矩阵中要查找到的某数。
//int row,col:存储该数所在的行、列值。
//(2)公有成员函数
//构造函数:初始化n的值为4,x、row、col为0。
//void input(int a[][4]):将一个矩阵赋给该对象中的数组。
//void find():在该对象存储的矩阵中查找值最小的数,保存该数及该数所在的行、列值到x、row、col中。
//void print():按行输出矩阵的值。
//(3)在主函数中测试该类,使用以下测试数据,输出矩阵的值,查找值最小的数并输出x、row、col的值。

代码

#include <iostream>
using namespace std;

class  Matrix
{
public:
    Matrix(int n = 4, int x = 0, int row = 0, int col = 0);
    void input(int a[][4]);
    void find();
    void print();
private:
    int p[4][4];
    int n;
    int x;
    int row, col;
};

Matrix::Matrix(int n, int x, int row, int col)
{

    this->n = n;
    this->x = x;
    this->row = row;
    this->col = col;
}

void Matrix::input(int a[][4])
{
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            p[i][j] = a[i][j];
        }
    }
}

void Matrix::find()
{
    int min_index1 = 0, min_index2 = 0;
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            if (p[i][j] < p[min_index1][min_index2])
            {
                min_index1 = i;
                min_index2 = j;
            }
        }
    }
    x = p[min_index1][min_index2];
    row = min_index1 + 1;
    col = min_index2 + 1;
}

void Matrix::print()
{
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            cout << p[i][j] << "  ";
        }
        cout << endl;
    }
    cout << "x= " << x << endl;
    cout << "row = " << row << endl;
    cout << "col = " << col << endl;
}

int main()
{
    int a[][4] = { 17,2,3,4,5,6,7,8,9,10,1,12,13,14,15,16 };
    Matrix m;
    m.input(a);
    m.find();
    m.print();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值