问答题

请使用VC6或使用[答题]菜单打开考生文件夹proj3下的工程proj3,其中声明的Matrix是一个用于表示矩阵的类。其成员函数transpose的功能是实现矩阵的转置运算。将矩阵A的行列互换,所得到的矩阵称为A的转置,记做AT。例如,若有3×3矩阵
则A的转置为
请编写成员函数transpose,以实现矩阵转置功能。 要求: 补充编制的内容写在“//********333********”与“//********666********”之间,不得修改程序的其他部分。 注意:程序最后将结果输出到文件out.dat中。输出函数writeToFile已经编译为obj文件,并且在本程序中调用。 //Matrix.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[i][j]; } void setElement (int i, int j, int value){ array[i][j] =value; } void transpose(); 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[i] [j]; } } }; void readFromFile (const char *, Matrix&); void writeToFile (char *, const Matrix&); //main.cpp #include <fstream> #include "Matrix.h" void readFromFile ( const char * filename, Matrix& m) { ifstream infile(filename); if (! infile) { cerr << "无法读取输入数据文件! \n"; return; } int d; for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) { infile >> d; m.setElement(i, j, d); } } voidMatrix::transpose() { //******** 333******** //******** 666******** } int main () { Matrix m; readFromFile("", m); m.show("Before transpose:"); m.transpose(); m.show("After transpose:"); writeToFile("",m); return 0; }

【参考答案】

for(int i=0; i<M; i++) //行从i等于0到m遍历 for(int j=0; j<i; j++) ......

(↓↓↓ 点击下方‘点击查看答案’看完整答案、解析 ↓↓↓)
热门 试题

问答题
请使用VC6或使用[答题]菜单打开考生文件夹proj2下的工程proj2,其中定义了Shape类和Point类。Shape类表示抽象的形状,其成员函数draw声明了显示形状的接口。Point是Shape的派生类,表示平面直角坐标系中的点,其成员函数draw用于在屏幕上显示Point对象;成员函数distance用于计算两个点之间的距离。提示:在平面直角坐标系中,点(x1,y2)和点(x2,y2)之间的距离为:d=;标准库函数spn用于求平方根。请在横线处填写适当的代码并删除横线,以实现上述类定义。此程序的正确输出结果应为: (3,0) (0,4) Distance=5 注意:只在横线处填写适当的代码,不要改动程序中的其他内容,也不要删除或移动“****found****”。 #include <iostream> #include <math.h> using namespace std; class Shape { public: ********** found********** ______ virtual ~Shape() {} }; class Point : public Shape { public: Point(double x, double y):x_(x), y_(y) {} virtual void draw() const; ********** found********** double distance(______) const { return sqrt ((x_- pt.x_)* (x_-pt.x_) + (y_ - pt.y_)* (y_- pt.y_)); } private: ********** found********** ______ }; void Point::draw() const { ********** found********** cout << ’(’<<______<< ’)’<< endl; } int main ( ) { Point* pt1 = new Point (3, 0); Point* pt2 = new Point (0, 4); Shape* s = pt1; a->draw(); s = pt2; a->draw(); cout << Distance = << pt1 -> distance(* pt2) << endl; delete pt1; delete pt2; return 0; }