关于读取数字的循环(透过输入非数字结束循环)
关于读取数字的循环(通过输入非数字结束循环)
#include<iostream>
const int Max = 5;
int main()
{
using namespace std;
double fish[Max];
cout<<"Please enter the weights of your fish."<<endl;
cout<<"You may enter up to "<<Max<<" fish <q to terminate>."<<endl;
cout<<"fish #1:";
int i=0;
while(i<Max&&cin>>fish[i])
{
if(++i<Max)
{
cout<<"fish #"<<i+1<<":";
}
}
double total = 0.0;
for(int j=0;j<i;j++)
{
total+=fish[j];
}
if(i==0)
{
cout<<"No fish"<<endl;
}
else
{
cout<<total/i<<"= average weight of "<<i<<" fish"<<endl;
}
cout<<"Done."<<endl;
cin.get();
return 0;
}
这是C++primer上的例子,6.13,但是我用vs却不能运行,也没有错误,求大神看一下
------解决方案--------------------
这是我的编译软件运行的结果是不是你想要的
#include<iostream>
const int Max = 5;
int main()
{
using namespace std;
double fish[Max];
cout<<"Please enter the weights of your fish."<<endl;
cout<<"You may enter up to "<<Max<<" fish <q to terminate>."<<endl;
cout<<"fish #1:";
int i=0;
while(i<Max&&cin>>fish[i])
{
if(++i<Max)
{
cout<<"fish #"<<i+1<<":";
}
}
double total = 0.0;
for(int j=0;j<i;j++)
{
total+=fish[j];
}
if(i==0)
{
cout<<"No fish"<<endl;
}
else
{
cout<<total/i<<"= average weight of "<<i<<" fish"<<endl;
}
cout<<"Done."<<endl;
cin.get();
return 0;
}
这是C++primer上的例子,6.13,但是我用vs却不能运行,也没有错误,求大神看一下
------解决方案--------------------