请打开考生文件夹下的解决方案文件proj3,其中定义的Matrix是一个用于表示矩阵的类。成员函数max_value的功能是求出所有矩阵元素中的最大值。例如,若有3×3矩阵 则调用max_value函数,返回值为3。请编写成员函数max_value。 要

admin2018-07-06  27

问题 请打开考生文件夹下的解决方案文件proj3,其中定义的Matrix是一个用于表示矩阵的类。成员函数max_value的功能是求出所有矩阵元素中的最大值。例如,若有3×3矩阵

则调用max_value函数,返回值为3。请编写成员函数max_value。
要求:
补充编制的内容写在“//*******333*******”与“//*******666*******”之间,不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中。输出函数writeToFile已经编译为Obj文件,并且在本程序中调用。
//Matfix.h
#include<iostream>
#include<iomanip>
using namespace std;
const int M=18;
conSt int N=18;
Class Matrix{
int array[M][N];
public:
Matrix( ){}
int getElement(int i,int j)const{return array[j];}
VOid setElement(int i,int j,int value){array[j]=value;}
int max value( )const;
void show(const char*s)const
{
cout<<endl<<s;
for(int i=0;i<M;i++)(
cout<<endl;
for(int j=0;j<N;j++)
cout<<setw(4)<<array
[j];
}
}
};
void readFromFile(const char*,Matrix&);
void writeToFile(char*,const Matrix&);
//main.cpp
#include"Matrix.h"
#include<fstream>
void readFromFile(const char*f,Matrix&m){
ifstream infile(f);
if(infile.fail( )){cerr<<"打开输入文件失败!";return;}
int k;
for(int i=0;i<M;i++)
for(int j=0;j<N;j++){
infile>>k;
m.setElement(i,j,k);
}
}
int Matrix::max_value( )const
{
//*******333*******

//*******666*******
}
int main( )
{
Matrix m;
readFromFile(" ",m);
m.show("Matrix:");
cout<<endl<<"最大元素:"<<m.maxvalue( )<<endl;
writeToFile(" ",m);
return0;
}

选项

答案int temp=0;//定义整数变量temp,并赋值为零 for(int i=0;i<M;i++)//遍历矩阵的行 for(int j=0;j<N;j++)//遍历短阵的列 if(temp<array[i][j])//如果temp小于array[i][j] temp=array[i][j];//把array[i][j]赋值给temp return temp;//返回temp

解析 主要考查考生对二维数组的掌握,题目要求成员函数max_value的功能是求出所有矩阵元素中的最大值。因此只要逐个元素比较即可,下标i和j作为矩阵行和列的标记,使用双层for循环来遍历数组中的所有元素。
转载请注明原文地址:https://kaotiyun.com/show/fAAp777K
0

最新回复(0)