问题 问答题

使用VC6打开考生文件夹下的工程RevProj8。此工程包含一个源程序文件 RevMain8.cpp。在该文件中,函数resort的功能是:能在一个数列中,对从指定位置开始的几位数,按相反顺序重新排列,并在主函数中输出新的序列。 请改正程序中的错误,使它能得到正确结果。 注意,不要改动main函数,不得删行或增行,也不得更改程序的结构。 源程序文件RevMain8.cpp中的程序清单如下: //RevMain8.cpp #include <instream> using namespace std; void resort(int arr[],int where,int amount); int main () { int number [20] ,where, arrount, i; cout<<"Input 20 numbers\n"; for (i=0; i<20; i++) cin>>number [i]; cout<<"How many do you want to sort: "; cin>>arrount; cout<<"\n where do you want to start: "; cin>>where; cout<<"old array as follow:\n"; for (i=0; i<20; i++) cout<<nmuber [i] <<" "; resort (number,where, arrount); cout<<"\n resorted array as follow:\n"; for (i=0; i<20; i++) cout<<number [i] <<" "; cout<<end1; return 0; } void resort(int array[],int where, int amount) {int *pi, *p2, temp;p1=&array [where-1];p2=&array [where-2+amount];/* * * * *FOUND * * * * */for (;p1<&array [where-1+amount/2]; ){/* * * * *FOUND * * * * */ *p1=*p2; *p2=*p1;}return; }

答案

参考答案:

解析:正确的resort()函数如下: void resort(int array[],int where,int amount) { int *p1,*p2,temp; p1=&array[where-1); p2=&array[where-2+amount]; for(;p1<&array[where-1+amount/2);p1++,p2--) { temp=*p1 *p1=*p2; *p2=temp; } return; } 程序中主函数没有错误。函数resort()中有两处错误; ①for循环中缺少循环变量控制条件。 ②for循环中两元素值的交换过程有误,程序中的代码不能完成两元素值的交换。

单项选择题
单项选择题