7.7
#include <iostream> 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 <iostream> 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个元素