操作题
请使用VC6或使用[答题]菜单打开考生文件夹proj3下的工程proj3,其中包含主程序文件main.cpp和用户定义的头文件Array.h,整个程序包含有类Array的定义和主函数main的定义。请把主程序文件中的Array类的成员函数Contrary()的定义补充完整,经补充后运行程序,得到的输出结果应该是:
58
5, 4, 3, 2, 1
0, 0, 8.4, 5.6, 4.5, 3.4, 2.3, 1.2
注意:只允许在“//********333********”和“//********666********”之间填写内容,不允许修改其他任何地方的内容。
//Array.h
#include <iostream>
using namespace std;
template<class Type, int m>
class Array { //数组类
public:
Array(Type b[], int mm) { //构造函数
for(int i=0; i<m; i++)
if(i <mm) a[i] =b[i];
else a[i] =0;
}
void Contrary();
//交换数组a中前后位置对称的元素的值
int Length() const{ return m;}
//返回数组长度
Type operator [] (int i) const {
//下标运算符重载为成员函数
if(i<0 || i>=m)
{cout<<'下标越界!'<<endl; exit(1);}
return a[i];
}
private:
Type a[m];
};
void writeToFile(const char * );
//不用考虑此语句的作用
//main.cpp
#include'Array.h'
//交换数组a中前后位置对称的元素的值
template <class Type, int m>
void Array <Type, m >::Contrary () {
//补充函数体
//********333********
//********666********
}
int main(){
int s1[5] ={1, 2, 3, 4, 5};
double s2[6] = {1.2, 2.3, 3.4, 4.5, 5.6, 8.4};
Array<int, 5> d1(s1,5);
Array<double, 8> d2(s2,6);
int i;
d1.Contrary(); d2.Contrary();
cout <<d1.Length () <<' <<d2. Length ()<<endl;
for(i=0; i<4; i++)
cout <<d1[i] <<',';
cout <<d1[4] <<endl;
for(i=0; i<7; i++)
cout <<d2[i] <<',';
cout <<d2 [7] <<endl;
writeToFile ('');
//不用考虑此语句的作用
return 0;
}
【正确答案】for(int i=0, j=m-1; i<j; i++, j--) {//i从0开始自加,j从数组最一位开始自减,条件是i<j,开始遍历数组a Type temp=a[i]; //把a[i]赋值给变量temp a[i]=a[j]; //把a[j]赋值给[j] a[j]=temp; //把temp赋值给a[j],最终佚a[i]与a[j]值的互换 }
【答案解析】[考点] 本题考查的是Array类,其中涉及构造函数、const函数和运算符重载。交换数组中前后对称的元素的值,要使用两个下标i和j,一个代表第一个元素,一个代表最后一个元素,交换后i++,j--即可。 主要考查考生对交换算法的掌握情况,根据题目对要完成的函数Contrary的要求:交换数组a中前后位置对称的元素的值。这里取下标i=0,即为数组中的第一个元素,j=m-1,即为数组中的最后一个元素,利用中间值temp交换元素的值,然后i逐次递增的同时j逐次递减,再交换,循环到i>j时停止交换即可。 主要考查考生对数组中元素交换的掌握情况,交换算法要使得两个下标i和j移动的范围能覆盖全部元素,同时要确定for循环的终止条件。