cinfish.cpp
来源: 分支语句和逻辑运算符
点击上方按钮打开代码编辑器和可视化视图
⚠️ 交互式运行提示
为了防止网页挂起,所有 cin 输入语句已被自动注释。请直接在代码编辑器中修改变量的值来进行测试。
书本配套例题
原始代码预览
// cinfish.cpp -- non-numeric input terminates loop
#include <iostream>
const int Max = 5;
int main()
{
using namespace std;
// get data
double fish[Max];
cout << "Please enter the weights of your fish.\n";
cout << "You may enter up to " << Max
<< " fish <q to terminate>.\n";
cout << "fish #1: ";
int i = 0;
while (i < Max && cin >> fish[i]) {
if (++i < Max)
cout << "fish #" << i+1 << ": ";
}
// calculate average
double total = 0.0;
for (int j = 0; j < i; j++)
total += fish[j];
// report results
if (i == 0)
cout << "No fish\n";
else
cout << total / i << " = average weight of "
<< i << " fish\n";
cout << "Done.\n";
// code to keep VC execution window open if q is entered
// if (!cin) // input terminated by non-numeric response
// {
// cin.clear(); // reset input
// cin.get(); // read q
// }
// cin.get(); // read end of line after last input
// cin.get(); // wait for user to press <Enter>
return 0;
}
运行结果 / 调试信息
等待编译...
Graph loading...
0 / 0