C++Primer Plus第七章--函数---c++的编程模块7.3编程练习7,指针传参的使用

这是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整型变量

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值