7.7
//7.修改程序清单7.7中的3个数组处理函数,使之使用两个指针参数来表示区间. //fill_array()函数不返回实际读取了多少个数字,而是返回一个指针,该指针 //指向最后被填充的位置;其他的函数可以将该指针作为第二个参数,以标识
//数据结尾。
#include
using namespace std;
double *Fill_array(double *arr);////因为是对数组进行操作,所以可以不用返回值;
void const Show_array(const double *arr,double *Epoint);
void Reverse_array(double *arr,double *Epoint);
const int MAX=10;
void main77()
{
double arr[MAX];
double *end=Fill_array(arr);//使end指向最后一个指针
Show_array(arr,end);
Reverse_array(arr,end);
system(“pause”);
}
double *Fill_array(double *arr)
{
double *p=arr;
int i=0;//用于记录输入了多少个数字
for(i=0;i<MAX;i++)
{
cout<<”\nPlease enter the “<<i+1<<” double values:”;
if((cin>>*(arr+i)))//如果输入非法值,跳出循环
{
p++;
continue;
}
else
break;
}
cout<<”\n you had input “<<i<<” values!”<<endl;
return p;
}
void const Show_array(const double *arr,double *end)
{
const double *p=arr;
cout<<”the array is:”<<endl;
for(int i=0;i<MAX&&p<end;i++)
cout<<*(p+i)<<” “;
cout<<”\nshow end!”<<endl;
}
void Reverse_array(double *arr,double *end)
{
double *p=arr;
int temp;
cout<<”\nnow Reverse the array!”<<endl;
for(int i=1;i<(end-arr)/2&&p<end;i++)
{
temp=*(p+i);
*(p+i)=*(end-i-1);
*(end-i)=temp;
}
cout<<”this is the new array:”<<endl;
Show_array(arr,end);
}
被这道题卡了好几天,因为不是很透彻地理解了关于函数指针的这一部分,只好上网找了下答案。 感谢http://blog.sina.com.cn/s/blog\_4e6b6c2f01000a0c.html帖子对我的帮助。 发现这个有些bug,现修改如下,如果编译器不支持c++11的,可以将nullptr换为NULL即可。
#include
using namespace std;
double *Fill_array(double *arr);////因为是对数组进行操作,所以可以不用返回值;
void const Show_array(const double *arr,double *Epoint);
void Reverse_array(double *arr,double *Epoint);
const int MAX=10;
int main()
{
double arr[MAX];
double *end=Fill_array(arr);//使end指向最后一个指针
Show_array(arr,end);
Reverse_array(arr,end);
}
double *Fill_array(double *arr)
{
double *p=arr;
int i=0;//用于记录输入了多少个数字
for(i=0;i<MAX;i++)
{
cout<<”\nPlease enter the “<<i+1<<” double values:”;
if((cin>>*(arr+i))){//如果输入非法值,跳出循环
p=arr+i;//使p指向当前被填充的位置
continue;
}
else{
if(i==0)//如果一个都不输入,返回一个空指针
return nullptr;
else
break;
}
}
cout<<"\\n you had input "<<i<<" values!"<<endl;
return p;
}
void const Show_array(const double *arr,double *end)
{
const double *p=arr;
if(end==nullptr)
cout<<”没有输入元素”<<endl;
else{
cout<<”the array is:”<<endl;
for(;p<=end;p++)
cout<<*p<<” “;
}
cout<<”\nshow end!”<<endl;
}
void Reverse_array(double *arr,double *end)
{
if(end==nullptr)
cout<<”数组内没有元素!”<<endl;
else{
cout<<”\nnow Reverse the array!”<<endl;
double *p=arr;
double *e=end;
int temp;
//注意循环条件
for(;p<e;p++,e–){
temp=*p;
*p=*e;
*e=temp;
}
cout<<”this is the new array:”<<endl;
Show_array(arr,end);
}
}
测试如下: 不输入任何元素: 输入四个元素:
输入5个元素
—————————————————————————————————————————————————— //写的错误或者不好的地方请多多指导,可以在下面留言或者给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。 转载请注明出处:https://www.royalchen.com/ author:royalchen Email:royalchen@royalchen.com ———————————————————————————————————————————————————
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/cprimerplus第六版课后编程题答案77/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!