这是7.7中三个函数的定义,这次作业就是修改这三个函数
// function prototypes
int fill_array(double ar[], int limit);
void show_array(const double ar[], int n); // don't change data
void revalue(double r, double ar[], int n);
看下具体的题目要求:
7.修改程序清单 7.7中的3个数组处理函数,使之使用两个指针参数来表示区间。
fill_array()函数不返回实际读取了多少个数字,而是返回一个指针,
该指针指向最后被填充的位置;其他的函数可以将该指
针作为第二个参数,以标识数据结尾。
三个函数的声明
int fill_array(double* pBeg, const double* const pEnd);
void revalue(double r, double* pBeg, const double* const pEnd);
void show_array(const double* pBeg, const double* const pEnd);
获取数据
// function prototypes
int fill_array(double* pBeg, const double* const pEnd)
{
using namespace std;
double temp;
int i;
i = 0;
while (pBeg < pEnd)
{
cout << "输入值#" << i++ << ": ";
cin >> temp;
if (!cin)
{
cin.clear();
while (cin.get() != '\n')
{
continue;
}
cout << "输入非法.\n";
break;
}
else if (temp < 0)
{
break;
}
*pBeg = temp;
++pBeg;
}
return i;
}
显示数组,单传的参数是指针
// the following function can use, but not alter,
// the array whose address is ar
void show_array(const double* pBeg, const double* const pEnd)
{
using namespace std;
for (int i = 0; pBeg < pEnd; pBeg++)
{
cout << "Property #" << (i + 1) << ": $";
cout << *pBeg << endl;
}
}
第三个函数的实现,很简单乘一个因子
// multiplies each element of ar[] by r
void revalue(double r, double* pBeg, const double* const pEnd)
{
while (pBeg < pEnd)
{
*pBeg *= r;
++pBeg;
}
#if 0
const double* const pBeg
这里说明一下,前面一个是给指针指向的内容不能复制,比如* pBeg,不能复制
后面一个const 是不能给指针本身复制
#endif
}
#pragma region 7.cpp 7.7
/*
*/
#if 1
#include<iostream>
int main()
{
using namespace std;
const int Max = 5;
double properties[Max];
int size = fill_array(properties, properties + Max);
show_array(properties, properties + size);
if (size > 0);
{
cout << "enter revaluation factor:";
double factor;
while (!(cin>>factor))
{
//非法输入
cin.clear();
while (cin.get() != '\n')
{
continue;
}
cout << "非法输入,请输入有效的数字";
}
revalue(factor, properties, properties + size);
show_array(properties, properties + size);
}
cout << "done.\n";
return 0;
}
#endif
#pragma endregion
本项目是复制标准答案来的,没有去细想,
发出来的时候,还是咨询看来一下代码,
不过这里还有一点疑问,就是第一个函数fill()说的是返回指针,参考答案返回的是一个int整型变量