c++ 用指针操作数组

#include <iostream>
using namespace std;
const int Max = 5;

double * fill_array(double * first, int size);
void show_array(double * first, const double * last);
void revalue(double r, double * first, const double * last);


int main() {
	double properties[Max];

	double * size = fill_array(properties, Max);
	show_array(properties, size);
	if (size > 0) {
		cout << "Enter revaluation factor: ";
		double factor;
		while (!(cin >> factor)) {
			cin.clear();
			while (cin.get() != '\n')
				continue;
			cout << "Bad input; Please enter a number: ";
		}
		revalue(factor, properties, size);
		show_array(properties, size);
	}
	cout << "Done.\n";
	return 0;
}

double * fill_array(double * first, int size) {
	double temp;
	int i;
	for (i = 0; i < size; i++) {
		cout << "Enter value #" << (i + 1) << ":";
		cin >> temp;
		if (!cin) {
			cin.clear();
			while (cin.get() != '\n')
				continue;
			cout << "Bad input; input process terminated.\n";
			break;
		}
		else if (temp < 0)
			break;
		else
			*(first+i) = temp;
	}
	return first + i - 1;
}

void show_array(double * first, const double * last) {
	double * pt;
	for (pt = first; pt <= last; ++pt) {
		cout << "Property #" << (pt-first+1) << ": $";
		cout << *pt << endl;
	}
}

void revalue(double r, double * first, const double * last) {
	double * pt;
	for (pt = first; pt <= last; ++pt) {
		*pt *= r;
	}
}

  

posted @ 2018-09-30 10:12  ranwuer  阅读(1093)  评论(0编辑  收藏  举报