实例:输入最多五只鱼(也可为三只,或四只)的重量,求平均值
#include <iostream>
const int MAX = 5;
using namespace std;
int main()
{
float fish[MAX], total = 0;
int i = 0;
cout << "Please enter the weights of your fish.\n"
<< "You may enter up to 5 fish <q to terminate>\n";
cout << "fish #1:";
while(i < MAX - 1 && cin >> fish[i])
{
i++;
cout << "fish #" << i + 1 << ":";
}
cin >> fish[MAX - 1];
for(int j = 0; j < i; j++)
total += fish[j];
cout << total/i << " = average weight of " << i << " fish" << endl << "Done1\n";
return 0;
}
在上例中,cin >> fish[i]实际上是一个cin方法函数调用,该函数返回cin。但是当cin位于测试条件中,则被转换为bool类型,如果输入成功,则被转换成true,如果输入不成功,则被转换成false。