#include
const int Max = 5;
// 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);
int main()
{
using namespace std;
double properties[Max];
int size = fill_array(properties, Max);
show_array(properties, size);
if (size > 0)
{
cout << "Enter revaluation factor: ";
double factor;
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();//为什么用两个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;
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;
}
应该是写重复了,一次就可以了,目的是让程序暂停
这段代码主函数结尾使用两次 cin.get() 是为了等待用户输入后,程序执行结束前能够停留在屏幕上,以便用户查看结果。
第一个 cin.get() 用于接收用户按下的 Enter 键,使屏幕暂停,等待用户输入,第二个 cin.get() 用于清除输入流中的残留字符,以便在程序退出之前不会留下任何未读的输入字符。
这种写法在程序的结尾处非常常见,它可以让程序在结束之前等待用户输入,以便用户可以看到程序的输出结果,而不是看到程序立即关闭的命令行窗口。
不知道你这个问题是否已经解决, 如果还没有解决的话: