如有失误之处,还恳请指教!!!
// arrfun3.cpp -- array functions and const
#include <iostream>
const int Max = 5;
// function prototypes
//函数原型,返回值为int类型,有两个参数,一个是double类型的数组,一个是int类型。
int fill_array(double ar[], int limit);
//函数原型,没有返回值,有两个参数,其中一个为不可修改的double类型的数组,一个是int类型的值
void show_array(const double ar[], int n); // don't change data
void revalue(double r, double ar[], int n);
int main()
{
using namespace std;
double properties[Max];
//将fill_array()函数的返回值赋值给变量size
int size = fill_array(properties, Max);
show_array(properties, size);
if (size > 0)
{
cout << "Enter revaluation factor: ";
double factor;
//这个循环条件意味着,如果cin>>factor是合理的,那么cin将会把输入的值赋给factor
//如果cin>>factor是不合理的,那么就会开启while函数体中的代码
while (!(cin >> factor)) // bad input
{
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";
// cin.get();
// cin.get();
return 0;
}
int fill_array(double ar[], int limit)
{
using namespace std;
double temp;
int i;
for (i = 0; i < limit; i++)
{
cout << "Enter value #" << (i + 1) << ": ";
cin >> temp;
//如果cin>>temp是不合理的,那么被输入的不合理的值将被留在队列中
//因此if(!cin)可以作为一个判断条件
if (!cin) // bad input
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
break;
}
else if (temp < 0) // signal to terminate
break;
ar[i] = temp;
}
return i;
}
// the following function can use, but not alter,
// the array whose address is ar
void show_array(const double ar[], int n)
{
using namespace std;
for (int i = 0; i < n; i++)
{
cout << "Property #" << (i + 1) << ": $";
cout << ar[i] << endl;
}
}
// multiplies each element of ar[] by r
void revalue(double r, double ar[], int n)
{
for (int i = 0; i < n; i++)
ar[i] *= r;
}