原程序如下:
#include<iostream>
using namespace std;
const int Max = 6;
double *fill_array(double *begin, double *end);
void show_array(double *begin, double *end);
double *revalue(double r, double *begin, double *end);
int main()
{
double properties[Max];
double *size = fill_array(properties, properties+Max);
show_array(properties, size);
cout << "Please enter the factor:" ;
double factor;
cin >> factor;
revalue(factor, properties, size);
show_array(properties, size);
system("pause");
return 0;
}
double *fill_array(double *begin, double *end)
{
double temp;
double *i = begin; // 还是没有搞懂为什么直接把begin赋值给*i,按道理说如果不存在*i是一种数据类型
int j = 0; // 而是地址的话,那么这样确实解释得通,*i是数,而i是地址,double * 不是数据类型而是地址
for (; i<end; i++)
{
cout << "enter the value #" << (j++ +1) << ":" ;
cin >> temp;
if (!cin || temp<0)
{
cin.clear();
while (cin.get() != '\n');
cout << "Bad input; Please enter a positive number(q to q): ";
cin >> temp;
if (!cin)
{
cout << "The input process terminated!" << endl;
break;
}
}
*i = temp;
}
return i;
}
void show_array(double *begin, double *end)
{
double *i = begin;
for (; i<end; i++)
cout << *i << endl;
}
double *revalue(double r,double *begin, double *end)
{
double *i = begin;
for (; i<end; i++)
{
*i *= r;
}
return i;
}
运行结果如下:
要注意的代码段如下:
for (; i<end; i++)
{
cout << "enter the value #" << (j++ +1) << ":" ;
cin >> temp;
if (!cin || temp<0)
{
cin.clear();
while (cin.get() != '\n');
cout << "Bad input; Please enter a positive number(q to q): ";
cin >> temp;
if (!cin)
{
cout << "The input process terminated!" << endl;
break;
}
}
*i = temp;
}
return i;
}
在后面重新输入的q和空格输入之后一直留在缓冲队列中,所以cin在读取时直接读取的q,由于不是数字,所以程序出错。在代码中加入清除和把空格读取了之后才能继续进行有效输入。
即:
if (!cin)
{
cout << "The input process terminated!" << endl;
cin.clear();
cin.get();
break;
}
则运行结果如下:
话说为什么我觉得自己的代码那么复杂呢?脑子不够用吧。